有人可以帮助我们吗?我们创建了一个扩展来搜索关键词的文本框,如果找到关键词,我们就想将文本写入另一个文本框。我们不确定如何在内容脚本中创建第二个发送响应(或者即使它是我们需要的发送响应),或者如何在后台脚本中访问它。代码如下。
内容脚本:
// Listen for messages
chrome.runtime.onMessage.addListener(function (msg, sender, sendResponse) {
console.log(msg);
// If the received message has the expected format...
if (msg.text === 'report_back')
{
// Call the specified callback, passing
// the web-page's DOM content as argument
sendResponse(document.getElementById('.........').innerHTML);
}
});
后台脚本:
var urlRegex = /^https?:\/\/(?:[^./?#]+\.)?stackoverflow\.com/;
// A function to use as callback
function doStuffWithDom(domContent) {
var search = false;
if (domContent.match(/......./gi))
{
window.alert('......');
}
else
{
var r = confirm("Search indicates no tasks listed!");
if (r == true) {
//Type Text Code
} else {
x = "You pressed Cancel!"; //We are aware this does not do anything
}
}
}
// When the browser-action button is clicked...
chrome.browserAction.onClicked.addListener(function (tab) {
// ...check the URL of the active tab against our pattern and...
// ...if it matches, send a message specifying a callback too
chrome.tabs.sendMessage(tab.id, {text: 'report_back'}, doStuffWithDom);
});
清单:
{
"manifest_version": 2,
"name": "Test Extension",
"version": "0.0",
"background": {
"persistent": false,
"scripts": ["background.js"]
},
"content_scripts": [{
"matches": ["*://*.com/*"],
"js": ["content.js"]
}],
"browser_action": {
"default_title": "Test Extension"
},
"permissions": ["activeTab"]
}
答案 0 :(得分:0)
为什么不将后台脚本中的逻辑放到内容脚本中?因为您只是在搜索dom并弹出警报窗口。
内容脚本:
var doStuffWithDom = function (domContent) {
if (domContent.match(/......./gi)) {
window.alert('......');
}
else {
var r = confirm("Search indicates no tasks listed!");
if (r == true) {
//Type Text Code
} else {
x = "You pressed Cancel!";
}
}
};
chrome.runtime.onMessage.addListener(function (msg, sender, sendResponse) {
if (msg.text === 'report_back') {
doStuffWithDom(document.getElementById('.........').innerHTML);
}
});
后台脚本:
chrome.browserAction.onClicked.addListener(function (tab) {
chrome.tabs.sendMessage(tab.id, { text: 'report_back' });
});
答案 1 :(得分:0)
似乎您正在从后台HTML页面中搜索Dom内容? 您确定内容在后台页面中吗?
您的内容脚本在“内部”(实际上是沙箱)浏览的HTML页面中执行。 我想你应该从内容脚本中搜索DOM ......