'Google Chrome Extensions - Clicking an icon calls a function
I've been trying to make an extension that would have an icon, which upon clicking would stop (all) tabs from loading.
I have this manifest file:
{
"name": "Stop Loading",
"version": "1.0",
"manifest_version": 2,
"description": "Stop loading all tabs in Chrome",
"browser_action": {
"default_icon": "greyclose.png"
},
"background_page": "background.html",
"content_scripts": [ {
"all_frames": true,
"js": [ "kliknuto.js" ],
"matches": [ "http://*/*", "https://*/*" ]
} ],
"permissions": [ "tabs", "http://*/*", "https://*/*" ]
}
In background.html I have this code:
chrome.browserAction.onClicked.addListener(function(tab) {
chrome.extension.sendRequest({reqtype: "get-settings"}, function(response) {
window.setTimeout("window.stop();", 0);
});
});
I'm not sure should I be putting the background.html code into a JavaScript file "kliknuto.js" or something else. Which function is called when you click the extension button in Chrome?
Solution 1:[1]
In your code, background.html is sending a query to itself (chrome.extension.sendRequest will not send to content scripts), and then, if/when it gets a reply, the background page is calling window.stop() on itself, rather than the tabs. What you really need is:
background.html:
...
chrome.browserAction.onClicked.addListener(function(tab) {
// get all tabs in all windows
chrome.windows.getAll({"populate":true}, function(winArray) {
for(var i = 0; i < winArray.length; ++i) {
for(var j = 0; j < winArray[i].tabs.length; ++j) {
var t = winArray[i].tabs[j];
// push code to each tab
chrome.tabs.executeScript(t.id, {"code":"window.stop();", "allFrames":"true"});
}
}
});
});
...
This solution uses executeScript in place of a content script.
EDIT with alternate solution:
Attach a content script to each tab that listens for orders from the backgroud page.
background.html:
...
chrome.browserAction.onClicked.addListener(function(tab) {
// get all tabs in all windows
chrome.windows.getAll({"populate":true}, function(winArray) {
for(var i = 0; i < winArray.length; ++i) {
for(var j = 0; j < winArray[i].tabs.length; ++j) {
var t = winArray[i].tabs[j];
// push code to each tab
chrome.tabs.sendRequest(t.id, {"order":"stop"});
}
}
});
});
...
kliknuto.js:
chrome.extension.onRequest(function(request) {
if(request.order == "stop") {
window.stop();
}
});
Make sure you add "run_at":"document_start" to the content_script block in your manifest so that the content script starts listening as soon as possible.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
