Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/420.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 消息外部的chrome扩展不工作_Javascript_Google Chrome Extension - Fatal编程技术网

Javascript 消息外部的chrome扩展不工作

Javascript 消息外部的chrome扩展不工作,javascript,google-chrome-extension,Javascript,Google Chrome Extension,显示 { "manifest_version": 2, "name": "sth", "description": "sth", "version": "0.1", "background": { "scripts": ["background.js"], "persistent": false }, "browser_action": { "default_icon": "icon.p

显示

{
    "manifest_version": 2,

    "name": "sth",
    "description": "sth",
    "version": "0.1",

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

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

    "externally_connectable": {
        "ids": [
            "mmaocogodokhpkellandkpdknpnihple"
        ],
        "matches": [
            "https://*.google.de/*"
        ],
        "accepts_tls_channel_id": false
    },

    "permissions": [
        "activeTab"
    ]
}
background.js

chrome.browserAction.onClicked.addListener(function(tab) {
    chrome.tabs.executeScript(null, {file: "content.js"});
});

chrome.runtime.onMessageExternal.addListener( function(request, sender, sendResponse) {
    console.log(request);
    return true;
});
content.js

console.log("content");
var msg = { text: "test" };
chrome.runtime.sendMessage("mmaocogodokhpkellandkpdknpnihple", msg, function() {
    console.log("content callback");
});
启用时,我单击图标并在控制台中看到“content”和“contentcallback”,但是请求没有记录在后台脚本的控制台中。我可能错过了什么


(Linux上的Chrome 44)

您自己的扩展内的消息不是外部消息。您需要有
onMessage
且不指定ID的常规无聊消息

// background.js
chrome.browserAction.onClicked.addListener(function(tab) {
    chrome.tabs.executeScript(null, {file: "content.js"});
});

chrome.runtime.onMessage.addListener( function(request, sender, sendResponse) {
    console.log(request);
    return true; // Why? This keeps the communication channel open waiting,
                 // and then you won't see "content callback"
});


事实上,也许返回
true
会让你感到困惑?当您计划异步调用
sendResponse
时需要它,因此
sendMessage
的回调在启动之前不会启动。

检查主窗口控制台。这就是content.js控制台记录信息的地方。为什么同时指定
id
匹配项
?没有任何意义。另外,还不清楚是否需要外部可连接,也许您可以通过正常的扩展消息来实现。@wOxxOm这很有意义。它允许两者兼而有之。但是,允许它作为自己的id并没有多大意义。谢谢Xan。我第一次尝试使用Message,但运气不好,这让我觉得外部会起作用。无法追溯我一开始做错了什么,但现在它起作用了。
// content.js
console.log("content");
var msg = { text: "test" };
chrome.runtime.sendMessage(msg, function() {
    console.log("content callback");
});