我无法在内容脚本和弹出窗口之间进行双向通信。
我可以与内容脚本进行通信,因此提醒"收到的消息正在显示"
但反馈提醒"已收到回复"没有出现。但收到的回复是#34;当我检查弹出窗口然后单击按钮时显示警告。
我的问题是,为什么我需要检查弹出窗口以获得反馈警报"收到回复"?如何在不检查弹出窗口的情况下获得响应?
弹出式HTML
<!doctype html>
<html>
<head>
<title>activity</title>
<script src="jquery.js"></script>
</head>
<body>
<button id="clickactivity">click</button>
<script src="popup.js"></script>
</body>
</html>
Manifest json
{
"manifest_version": 2,
"name": "Such Activity",
"description": "Wow",
"version": "1.0",
"browser_action": {
"default_icon": "icon.png",
"default_popup": "popup.html"
},
"permissions": [
"activeTab",
"tabs",
"http://*/*",
"https://*/",
"<all_urls>"
],
"content_scripts": [
{
"matches": [ "https://*/*", "http://*/*" ],
"js": [ "jquery.js", "content_script.js" ]
}
]
}
弹出式HTML
<!doctype html>
<html>
<head>
<title>activity</title>
<script src="jquery.js"></script>
</head>
<body>
<button id="clickactivity">click</button>
<script src="popup.js"></script>
</body>
</html>
Popup JS
function injectTheScript() {
chrome.tabs.query({ active: true, currentWindow: true }, function (tabs) {
chrome.tabs.sendMessage(tabs[0].id, { sender: "Hi" }, function (response) {
if (response.receiver == "Hello") {
alert("Response recieved");
}
});
});
}
document.getElementById('clickactivity').addEventListener('click', injectTheScript);
内容脚本JS
$(document).ready(function () {
chrome.runtime.onMessage.addListener(
function (request, sender, sendResponse) {
if (request.sender == "Hi") {
alert("Message Received");
sendResponse({ receiver: "Hello" });
}
});
});