Chrome 消息传递 API 不起作用

Chrome Message Passing API does not work

我正在尝试创建一个扩展程序,它会告诉我是否在我在选项卡中显示的当前网站上使用了某个脚本。

我有一个内容脚本来查看哪些脚本用于向我的后台脚本发送消息,如果切换选项卡并更改我的扩展图标以查看是否使用脚本,该脚本会处理通知。

这是我的内容脚本 (load.js):

chrome.runtime.sendMessage({script_found: checkScript()});
function checkScript() {
    var script_found = true;
    var length = document.getElementsByTagName("script").length;

    for (var i = 0; i < length; i++) { 
        var list = document.getElementsByTagName("script")[i].src;
        var t = list.toString();
        if (t.length > 1) {
            if((t.indexOf("edge") != -1) || (t.indexOf("prototype") != -1)) {
                script_found = false;
            }
        }
    }

    return script_found;
}

chrome.runtime.onMessage.addListener(
  function(request, sendResponse) {
    if(request.tabSwitch == true) {
        sendResponse({script_found: checkScript()});
    }
});

这是我的后台服务 (background.js):

chrome.tabs.onActivated.addListener(tabSwitch);

function tabSwitch() {
    chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
        chrome.tabs.sendMessage(tabs[0].id, {tabSwitch: "true"},function(response) {
            refreshIcon(response.script_found);
        });
    });
}

chrome.runtime.onMessage.addListener(
  function(request) {
    refreshIcon(request.script_found);
  });


function refreshIcon(script_found) {
    if(script_found) {
        chrome.browserAction.setIcon({path:"good.png"})
    } else if(!script_found) {
        chrome.browserAction.setIcon({path:"error.png"})
    }
}

我真的不知道为什么它在 tabSwitch 上不起作用。加载网站时它工作正常,但当我在选项卡之间切换时它不会。

希望对您有所帮助! 提前致谢!!

编辑: 这是我的清单 (manifest.json):

{
  "manifest_version": 2,

  "name": "Script Hunter",
  "description": "This extension shows if certain scripts are used on this page.",
  "version": "1.0",

  "content_scripts": [{
    "matches": ["<all_urls>"],
    "js": ["load.js"],
    "run_at": "document_idle"
  }],

  "background": {"scripts": ["background.js"]},

  "browser_action": {
    "default_icon": "good.png"
  },

  "permissions": [
    "tabs",
    "activeTab",
    "https://ajax.googleapis.com/"
  ]
}

再次感谢!

  1. 对于background.js,不需要查询活动标签,直接使用chrome.tabs.onActivated的回调参数即可。 (正如@wOxxOm 在评论中提到的,在这里使用 tabSwitch: true

    chrome.tabs.onActivated.addListener(tabSwitch);
    
    function tabSwitch(activeInfo) {
        chrome.tabs.sendMessage(activeInfo.tabId, {tabSwitch: true},function(response) {
            refreshIcon(response.script_found);
        });
    }
    
  2. 在load.js中,chrome.runtime.onMessage回调的第三个参数是sendResponse,但是你只指定了两个参数。

    chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
        ...
    });