正在从 Popup.html 向 Listener.js 发送请求

Sending requests from Popup.html to Listener.js

我有以下内容:

popup.html:

        <!DOCTYPE html> 
    <html>
    <head>
    <style>
      body { width: 700px; }
      textarea { width: 250px; height: 100px;}
    </style>
    <script>
        function sendMessage(){
            chrome.tabs.getSelected(null, function(tab) {
                chrome.tabs.sendRequest(tab.id, {method: "fromPopup", tabid: tab.id});});
    }
    </script>
    </head>
    <body>
    <button onclick="sendMessage(); ">Test</button>
    </body>
    </html>

manifest.json:

        {
    "manifest_version": 2,
    "name": "ROBLOX Hub",
    "version": "1.1",
    "description": "A compilation of scripts to interact with the ROBLOX site.",
    "browser_action": {
        "default_icon": "icon.png",
        "default_popup": "popup.html"
    },
    "permissions": [
        "tabs",
        "<all_urls>"
     ],
    "content_scripts": [
    {
        "matches": ["<all_urls>"],
        "js": [ "jquery.min.js", "listener.js"],
        "run_at": "document_start",
        "all_frames": true
      }]
    }

listener.js:

chrome.extension.onRequest.addListener(function(request, sender, sendResponse) {
if (request.method == "fromPopup") {
alert("I DID IT MOM")
});

但是,当我点击 "test" 时,它似乎没有发出警报 ("I DID IT MOM")。我这样做正确吗?我猜不是,因为我的脚本不起作用。基本上它应该向内容脚本发送消息,"listener.js"。 Listener.js 在所有页面上都是 运行(如清单中所示)并且 popup.html 应该能够向它发送请求,触发 "I DID IT MOM" 的警报。我的脚本有什么问题?提前感谢您的帮助。

CSP policy 起,Chrome 扩展中不允许内联 Js。而不是这样做,你应该在 html 中引用你的 js 代码,比如 <script src="popup.js"></script>,修改你的按钮标签:<button>Test</button> 并将下面的代码放入你的 popup.js.

document.addEventListener('DOMContentLoaded', function () {
  document.querySelector('button').addEventListener('click', clickHandler);
  sendMessage();
});

另请记住 chrome.tabs.sendRequest and chrome.extension.onRequest were deprecated and use chrome.runtime.sendMessage and chrome.runtime.onMessage