浏览器扩展通信问题为什么只有特定页面可行,其它页面报错(Could not establish connection. Receiving end does not exist)?

  • 写了个网页音乐播放器扩展,本意是想不需要切换到音乐网页去点击切换歌曲,希望扩展在任意网页点击可切换该音乐网页的歌曲。
  • 现在遇到的问题是,扩展在在那个音乐网页就可以正常使用(=.=),在其它网页都报错:Unchecked runtime.lastError: Could not establish connection. Receiving end does not exist.

manifest.json

{
    "name": "播放器",
    "version": "0.0.0.1",
    "manifest_version": 3,
    "description": "用于切换播放模式及控制下一首歌曲的扩展程序",
    "icons": {
        "128": "icons/128x128.png"
    },
    "action": {
        "default_popup": "popup/popup.html"
    },
    "content_scripts": [{
        "matches": ["音乐播放网页"],
        "js": ["lib/jquery.min.js", "content-scripts/content.js"]
    }],
    "externally_connectable": {
        "ids": ["ebjnejafkk*********plickhfn"],
        "matches": ["音乐播放网页"]
    },
    "permissions": [
        "tabs",
        "scripting"
    ],
    "web_accessible_resources": [{
        "resources": ["images/*.jpeg"],
        "matches": ["<all_urls>"]
    }]
}

content.js

//向扩展(popup.js)发送消息
 chrome.runtime.sendMessage()
// 接收来自扩展(popup.js)的消息
 chrome.runtime.onMessage.addListener()

popup.js

//向content.js(即音乐网页)发送消息
 chrome.tabs.sendMessage()
//接收来自content.js(即音乐网页)的消息
chrome.runtime.onMessage.addListener
阅读 6.4k
2 个回答
"background": {
    "service_worker": "background.js"
},

然后,在background.js:

chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
    if (message.from === 'popup') {

        chrome.tabs.query({url: '音乐播放网页URL'}, (tabs) => {
            if (tabs.length) {
                chrome.tabs.sendMessage(tabs[0].id, message, sendResponse);
            }
        });
    } else if (message.from === 'content') {
  
        chrome.runtime.sendMessage(message);
    }
    return true; 
});

之前一直不懂为什么popup与content可以通信,为什么只有特定页面能行的通,虽然楼上给了解决方案,但是还是不知道为什么。最后看到这篇博主的文才明白【干货】Chrome插件(扩展)开发全攻略

  • content_scripts向popup主动发消息的前提是popup必须打开!否则需要利用background作中转;
  • 如果background和popup同时监听,那么它们都可以同时收到消息,但是只有一个可以sendResponse,一个先发送了,那么另外一个再发送就无效;
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题