将请求从Popup.html发送到Listener.js

时间:2015-06-12 23:05:28

标签: javascript google-chrome google-chrome-extension

我有以下内容:

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

然而,当我点击“测试”时,它似乎没有警告(“我已经死了”)。我这样做了吗?我猜不是因为我的脚本不起作用。基本上它应该向内容脚本“listener.js”发送消息。 Listener.js正在所有页面上运行(如清单中所示),popup.html应该能够向其发送请求,触发“I DID IT MOM”的警报。我的脚本出了什么问题?感谢您的帮助。

1 个答案:

答案 0 :(得分:1)

CSP policy起,Chrome扩展程序中不允许使用内联Js。不应该这样做,您应该在<script src="popup.js"></script>等html中引用您的js代码,修改您的按钮代码:<button>Test</button>并将代码放在popup.js中。

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

另请注意,chrome.tabs.sendRequestchrome.extension.onRequest已被弃用,请改用chrome.runtime.sendMessagechrome.runtime.onMessage