我正在尝试通过单击按钮发送消息,即使在我的网站上也是如此,该网站是通过 chrome 扩展程序在选项卡中打开的。
但是,我无法从网页中获取任何消息,并且出现端口错误。
我的 content.js:
var port = chrome.extension.connect();
port.onMessage.addEventListener("message", function(event) {
// We only accept messages from ourselves
if (event.source != window)
return;
if (event.data.type && (event.data.type == "FROM_PAGE")) {
console.log("Content script received: " + event.data.text);
port.postMessage(event.data.text);
}
}, false);
chrome.tabs.onMessage.addListener(function(tabId, changeInfo, tab) {
alert(changeInfo);
});
Popup.js
$("#linkify").click(function() {
chrome.tabs.create({
'url': 'http://localhost:3000/signin'
}, function(tab) {
// Tab opened.
chrome.tabs.executeScript(tab.id, {
file: "jquery.js"
}, function() {
console.log('all injected');
chrome.tabs.executeScript(tab.id, {
file: "content.js"
}, function() {
console.log('all injected');
chrome.tabs.sendMessage(tab.id, function() {
console.log('all injected');
});
});
});
});
//getlink();
});
});
function checkUserAuth() {
console.log(localStorage.getItem("apiKey"));
if (localStorage.getItem("apiKey") != null) {
document.getElementById('openBackgroundWindow').style.visibility = 'hidden';
}
}
var port = chrome.extension.connect({
name: "Sample Communication"
});
port.postMessage("Hi BackGround");
port.onMessage.addListener(function(msg) {
console.log("message recieved" + msg);
});
我的背景.js
chrome.extension.onMessage.addListener(
function(request, sender, sendResponse) {
console.log(sender.tab ?
"from a content script:" + sender.tab.url :
"from the extension");
});
从 Web url 发送消息的脚本:
document.getElementById("theButton").addEventListener("click", function() {
console.log("message being sent");
window.postMessage({ type: "FROM_PAGE", text: "Hello from the webpage!" }, "*");
}, false);
我在哪里出错了,我没有收到任何消息?