谷歌浏览器扩展程序 - 单击图标可调用函数

Google Chrome Extensions - Clicking an icon calls a function

本文关键字:调用 函数 图标 单击 扩展 程序 谷歌浏览器      更新时间:2023-09-26

我一直在尝试制作一个带有图标的扩展,单击该图标将停止加载(所有)选项卡。

我有这个清单文件:

{
  "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://*/*" ]
}

在后台.html我有以下代码:

chrome.browserAction.onClicked.addListener(function(tab) {
  chrome.extension.sendRequest({reqtype: "get-settings"}, function(response) {
    window.setTimeout("window.stop();", 0);
  });
});

不确定我是否应该将背景.html代码放入JavaScript文件"kliknuto.js"或其他东西中。当您在 Chrome 中点击扩展程序按钮时会调用哪个函数?

在你的代码中,background.html 正在向自身发送查询(chrome.extension.sendRequest不会发送到内容脚本),然后,如果/当它得到回复时,后台页面会调用 window.stop() 自身,而不是选项卡。 您真正需要的是:

背景.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"});
            }
        }
    });
});
...

此解决方案使用executeScript代替内容脚本。

使用替代解决方案进行编辑:

将内容脚本附加到每个选项卡,以侦听来自背景页面的订单。

背景.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();
    }
});

请确保将"run_at":"document_start"添加到清单中的content_script块,以便内容脚本尽快开始侦听。