有人能帮我们吗?我们已经创建了一个扩展,用于搜索文本框中的关键字,如果找到关键字,则希望将文本写入另一个文本框。我们不确定如何在内容脚本中创建第二个发送响应(或者即使它是我们需要的发送响应),也不确定如何在后台脚本中访问它。下面列出的代码。
内容脚本:
// 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"]
}发布于 2016-02-25 01:19:47
为什么不把后台脚本中的逻辑放到内容脚本中呢?因为您只是在搜索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' });
});发布于 2016-02-25 12:40:38
似乎您正在从背景HTML页面中搜索Dom内容?您确定内容在后台页面中吗?
您的内容脚本执行“在”(实际上是沙箱)浏览HTML页面。我想你应该从内容脚本中搜索DOM .
https://stackoverflow.com/questions/35601208
复制相似问题