我很难理解如何在 Chrome 扩展中传递信息,特别是具有特定 ID 的 HTML 元素的值,我尝试过 extension documentation但这对我几乎没有帮助。
最终,我尝试构建的扩展将读取动态生成表单的特定页面。该表格有一个 <input id="foo">
标签;当 <input>
生成后我希望内容脚本传递一条消息,其中包含另一个 <div id="bar">
中包含的文本在与背景页面相同的页面上。一旦到达后台页面,文本将被解析,并且 switch 语句将在输入下方创建一个 div,并将其着色为红色或绿色,并填充一些文本。
但是,目前我正在努力解决消息传递以及如何确定我的内容脚本实际在做什么的问题。此时,有人可以告诉我如何在用户选项卡中单击按钮后简单地向后台页面发送消息并使用按钮的 id 执行alert() 吗?
这是我到目前为止所拥有的:
manifest.json
{
"manifest_version": 2,
"name": "Authinator",
"description": "extension",
"version": "1.0",
"background": {
"scripts": ["background.js"]
},
"browser_action":{
"default_icon": "icon.png"
},
"permissions":[
"tabs",
"activeTab",
"https://ajax.googleapis.com/"
],
"content_scripts": [
{
"matches": [ "http://*/*", "https://*/*"],
"js": [ "auth.js", "jquery.min.js"]
}]
}
背景页面(background.js):
//alerts when extension icon clicked
chrome.browserAction.onClicked.addListener(function(tab) { alert('icon clicked')});
//trying to alert when button is clicked
chrome.runtime.onMessage.addListener(function(response, sender, sendResponse){
alert(response);
})
内容脚本(auth.js):
var someButton = document.findElemendById("foo");
someButton.addEventListener("click", function(button){
chrome.runtime.sendMessage(button.id);
})
这里的任何帮助或指导将不胜感激。谢谢大家!
最佳答案
您正在以字符串
的形式发送消息,您的消息应该是一个对象,否则它将把您的第一个参数视为扩展程序ID。
阅读 here .
试试这个:
chrome.runtime.sendMessage({buttonID:button.id});
然后,在接收端:
alert(response.buttonID);
应该可以。
我希望这会有所帮助。
关于javascript - Chrome 扩展程序 : Passing DOM Information to background page/script,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35760673/