Chrome 扩展程序输入文本问题

Chrome Extension Input Text Issue

本文关键字:文本 问题 输入 程序 扩展 Chrome      更新时间:2023-09-26

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

内容脚本:

// 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"]
   }

为什么不将后台脚本中的逻辑放入内容脚本?由于您只是在搜索 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' });
});

似乎您正在从后台 HTML 页面搜索 Dom 内容?您确定内容在背景页面中吗?

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