Chrome Extension 背景運行與通信


需要在按下插件圖示後.自動讀取目前所在頁中指定位置的所有的連結.
之後傳送到背景將有連結以 Tab 開啟.
再將每個頁面裡匹配指定樣式的連結作替換.
最後傳送到指定的主機裡面作連結破解等等.
記錄一下

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
{
"manifest_version": 2,
"background": {
"scripts": ["background.js"]
},
"browser_action": {
"default_title": "",
"default_icon": "icon_128.png"
},
"content_scripts": [{
"matches" : ["http://*/*"],
"js": ["jquery.js", "content_script.js"],
"run_at": "document_end"
}],
"permissions": [
"tabs"
]
}
1
2
3
4
5
6
7
8
9
10
11
chrome.browserAction.onClicked.addListener(function(tab) {
chrome.tabs.sendMessage(tab.id, {
action: "getAllLinks"
});
});

chrome.extension.onMessage.addListener(function(request, sender, sendResponse) {
chrome.tabs.create({
url: request.link
});
});
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
chrome.extension.onMessage.addListener(function(request, sender, sendResponse) {
if (request.action == "getAllLinks") {
Array.prototype.slice.call(document.querySelectorAll(".threadlist table tbody .common span a")).forEach(function(link) {
chrome.extension.sendMessage({
"link": link.href
});
});
}
});

$(".t_msgfont img:lt(2)").each(function() {
var enable_site = [
'http://sub.domain.com/server-a/extension/script.php',
'http://sub.domain.com/server-b/extension/script.php',
];
var random_site = enable_site[parseInt((Math.random() * enable_site.length))]

$(this).prop("src", random_site + "?r=" + $(this).prop("src").replace("http://t", "http://i"));
});