Chrome 扩展输入文本问题

Chrome Extension Input Text Issue

有人可以帮助我们吗?我们创建了一个扩展来搜索文本框的关键字,如果找到关键字,我们就想将文本写入另一个文本框。我们不确定如何在内容脚本中创建第二个发送响应(或者即使它是我们需要的发送响应)或如何在后台脚本中访问它。代码如下。

内容脚本:

// 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?:\/\/(?:[^./?#]+\.)?Whosebug\.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"]
   }

为什么不把后台脚本中的逻辑放到内容脚本中呢?由于您只是搜索 dom 并弹出警报 window.

内容脚本:

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' });
});

您似乎是从后台 HTML 页面搜索 Dom 内容? 您确定内容在后台页面内吗?

您的内容脚本已执行 "within"(实际上是沙盒)浏览了 HTML 个页面。 我猜你应该从内容脚本中搜索 DOM...