我正在开发一个 chrome 扩展,需要将消息从扩展背景页面发送到内容脚本,但无论我做什么,我都会收到以下错误: “未检查的 runtime.lastError:无法建立连接。接收端不存在。”
后台脚本正在发送的消息正在由一个 API 获取,该 API 在每次 url 更改时运行。
这是 manifest.json 文件:
{
"manifest_version": 2,
"name": "tool",
"description": "help tool",
"version": "1.0",
"icons": {
"16": "icons/icon16.png",
"32": "icons/icon32.png",
"48": "icons/icon48.png",
"128": "icons/icon128.png"
},
"page_action": {
"default_icon": "icons/icon128.png",
"default_popup": "src/popup.html",
"default_title": "tool"
},
"background": {
"scripts": [
"src/background.js"
],
"persistent": true
},
"web_accessible_resources": [
"src/content.css"
],
"content_scripts": [
{
"matches": [
"https://*"
],
"js": [
"src/jquery-3.4.1.min.js",
"src/content.js"
],
"css": [
"src/content.css"
]
}
],
"permissions": [
"tabs",
"Api URL"
]
}
这是我在后台和内容脚本中使用的代码:
background.js- callApi 通过 chrome.tabs.onUpdated.addListener 函数在每次 url 更改时被调用:
chrome.tabs.onUpdated.addListener(() => {
chrome.tabs.query({active: true, currentWindow: true},function(tabs) {
var tab = tabs[0];
var url = tab.url;
var para = "url=" + url
console.log(para)
callApi(para)
})
})
const callApi = (para) => {
var url = "API URL" + para
fetch(url)
.then((response) => {
return response.text();
})
.then((data) => {
console.log(data);
connectToCurrentTab(data);
})
}
function getCurrentTabId(cb) {
var query = {active: true, currentWindow: true};
chrome.tabs.query(query, function(tabArray) {
cb(tabArray[0].id)
});
}
function connectToCurrentTab (data) {
getCurrentTabId(function(currentTabId) {
var port = chrome.tabs.connect(currentTabId, {name: "knock"})
port.postMessage(data);
port.onMessage.addListener((msg) => {
return true;
});
});
}
内容.js:
chrome.runtime.onConnect.addListener(port => {
console.log('connected ', port);
if (port.name === 'knock') {
port.onMessage.addListener(function(msg) {
var data = JSON.parse(msg)
port.postMessage({data: "received"});
});
}
});
我能够在内容脚本中获取数据,但它也显示错误。谁能帮我解决这个问题?任何帮助是极大的赞赏。