建立内容脚本和后台页面之间的通信链接
使用 javascript 开发 chrome 扩展是我的大学项目之一。
我不知道如何使用消息传递在内容脚本和后台页面之间建立通信链接。我需要一些帮助来建立连接
background.html
chrome.tabs.getSelected(null, function(tab) {
chrome.tabs.sendRequest(tab.id, {method: "getHTML"}, function(response) {
console.log(response.data);
});
});
content_script.js
chrome.extension.onRequest.addListener(function(request, sender, sendResponse) {
if (request.method == "getHTML")
sendResponse({data: document.getElementById('header').innerHTML});
else sendResponse({});
});
Developing a chrome extension using javascript is one of my university projects.
I don't know how to establish a communication link between content script and background page using messaging. I need some help in this establishing the connection
background.html
chrome.tabs.getSelected(null, function(tab) {
chrome.tabs.sendRequest(tab.id, {method: "getHTML"}, function(response) {
console.log(response.data);
});
});
content_script.js
chrome.extension.onRequest.addListener(function(request, sender, sendResponse) {
if (request.method == "getHTML")
sendResponse({data: document.getElementById('header').innerHTML});
else sendResponse({});
});
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
几个主要问题:
header
的某些元素。此类 ID 由网站设计者自行决定,因此实际上很少有页面(包括 Google)拥有该 ID。也许可以选择更通用的内容,例如页面标题 (document.title
)。header
元素的 Google 页面的问题之外),您只是没有捕获 浏览器操作点击事件。然而,如果它是一些注入的按钮,那就相反了。你想要什么(浏览器操作版本)
background.html(内联):
content_script.js
你可能想要什么(注入按钮点击版本)
background.html:
content_script.js:
回复下面评论的代码
非常重要的建议: Chrome 的开发者参考可能是最友好的参考之一。如果您想了解
chrome.*
API 的哪些部分可用,请从这里开始。下面评论的第二次回复代码
background.html
content_script.js
A few major issues:
header
. Such IDs are at the discretion of the site designer, so very few pages actually do have that (including Google). Maybe go for something a little more universal, like the title of the page (document.title
).header
), you're just not capturing the browser action click event. If it's some injected button, however, it's the other way around.What you want (browser action version)
background.html (inline):
content_script.js
What you might want (injected button click version)
background.html:
content_script.js:
Code for response to comment below
Very important recommendation: Chrome's developer reference is probably one of the friendliest out there. If you want to know what parts of the
chrome.*
API are available, start there.Code for second response to comment below
background.html
content_script.js