【发布时间】:2021-05-13 01:41:24
【问题描述】:
我有这个问题。我看到了这个question 并尝试了它的解决方案,但它似乎不起作用。错误消失了,但代码没有做它应该做的事情。
所以,基本上,我有一个后台脚本,它使用 XMLHTTPSrequest 在所有 http 或 https 页面中注入内容脚本。
background.js:
chrome.browserAction.onClicked.addListener(function (event) {
show_floater = !show_floater;
// inject content script in tabs
let xhr = new XMLHttpRequest();
xhr.open("GET", "https://127.0.0.1/js/test1.js", true);
xhr.onreadystatechange = function () {
if (xhr.readyState == 4) {
chrome.tabs.query({ currentWindow: true }, (tabs) => {
tabs.forEach(function(e) {
if (/http:/.test(e.url) || /https:/.test(e.url)) {
chrome.tabs.executeScript(e.tabId, { code: xhr.responseText }, () => {
connect(show_floater);
console.log(e.url);
});
}
else
console.log('e: ' + e.url);
});
});
}
}
xhr.send();
});
内容脚本然后在页面上执行它的魔法,并在用户操作发生时将消息发送回 bg。
content.js
chrome.runtime.sendMessage({}, function (response) {
console.log('sent');
let msgData = { text: "am I connected?" };
chrome.runtime.sendMessage(JSON.stringify(msgData));
});
下面是 bg 处理消息的方式:
chrome.runtime.onMessage.addListener(function (msg, sender, sendResponse) {
console.log('I AM HERE');
chrome.tabs.query({ active: true, currentWindow: true }, (tabs) => {
if (/http:/.test(e.url) || /https:/.test(e.url)) {
const port = chrome.tabs.connect(tabs[0].id);
msg = JSON.parse(msg);
if (msg.text == "am I connected?") {
//do stuff
}
}
});
// return true;
});
我正在查看的答案是在最后添加一个“返回真”。我试过了,错误消失了,但是 console.log 没有出现……哈哈!
【问题讨论】:
标签: javascript google-chrome-extension sendmessage content-script