Google chrome extension 无法从内容脚本获取响应
manifest.jsonGoogle chrome extension 无法从内容脚本获取响应,google-chrome-extension,message,Google Chrome Extension,Message,manifest.json { "name":"Word Replacer", "description" : "Changes One word to another", "version": "1.0", "manifest_version": 2, "permissions" : ["tabs"], "browser_action":{ "default_icon":"images/16.png", "defau
{
"name":"Word Replacer",
"description" : "Changes One word to another",
"version": "1.0",
"manifest_version": 2,
"permissions" : ["tabs"],
"browser_action":{
"default_icon":"images/16.png",
"default_popup":"popup.html"
},
"background":{
"scripts":["background.js"]
},
"icons":{
"16":"images/16.png",
"48":"images/48.png",
"128":"images/128.png"
},
"content_scripts":[{
"matches" : ["http://*/*", "https://*/*"],
"js":["content_script.js"],
"run_at" : "document_end"
}]
}
popup.html
<!DOCTYPE html>
<html>
<head>
<title>Word Replacer</title>
<script src="popup.js"></script>
</head>
<body style="width: 200px;" id="body">
<form id="replaceWord" method="POST">
Enter Old Word: <input type="text" name="oldWord" id="old">
Enter New Word: <input type="text" name="newWord" id="new">
<button type="submit" value="Change Word">CHange</button>
</form>
</body>
</html>
content_script.js
chrome.runtime.onMessage.addListener(function(response, sender, sendResponse){
sendResponse({value : "hello"});
});
试图从内容脚本接收对弹出窗口的响应,但没有得到响应。
在弹出窗口中,我有正确的标签id,但我没有得到任何响应。
为什么会这样?请提供帮助。您的
onMessage.addListener
呼叫可能在消息发送后发生。如果是这样,它将不会听到消息。@ZachSadler那么我如何纠正它?表单提交将导航页面,因此sendMessage
中的响应处理程序函数将永远不会运行。如果您取消提交(通过submit
处理程序中的return false
),我想它会像您期望的那样工作。@apsillers,仍然不工作。您的用户交互从用户单击browserAction
按钮开始,因此,应该为内容脚本注入manifest.jsoncontent\u脚本
entry,而不是manifest.json。这样,您的内容脚本就不会被注入到每个页面中等待使用,从而给浏览器带来负担。使用chrome.tabs.executeScript()
,脚本可以在注入时开始运行。
chrome.runtime.onMessage.addListener(function(response, sender, sendResponse){
sendResponse({value : "hello"});
});