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

小飞侠007

> * 写了个网页音乐播放器扩展,本意是想不需要切换到音乐网页去点击切换歌曲,希望扩展在任意网页点击可切换该音乐网页的歌曲。 > * 现在遇到的问题是,扩展在在那个音乐网页就可以正常使用(=.=),在其它网页都报错: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": [""] }] } 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

阅读量:286

点赞量:19

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