Chrome 扩展:SendMessage 问题

Chrome Extension : Issue with SendMessage

我正在尝试根据 xhr 调用的输出更改页面内容。我正在从 content.js 发送一条消息,在后台 js 文件中调用 xrh,然后将输出传递给 content.js,这会改变页面的内容。

根据我的 content.js 文件,我正在执行以下操作。

var s = document.createElement('script'); 
s.src = chrome.extension.getURL('src/content/main.js'); 
(document.head || document.documentElement).appendChild(s);

在我main.js我在做

  chrome.runtime.sendMessage({
    method: 'GET',
    action: 'xhttp',
    url: myurl
  }, function(responseText) {
      console.log("Response Text is ", responseText);
  });

在我的 bg.js 中,我有以下内容

chrome.runtime.onMessage.addListener(function(request, sender, callback) {
    if (request.action == "xhttp") {
        var xhttp = new XMLHttpRequest();
        var method = request.method ? request.method.toUpperCase() : 'GET';
        xhttp.onload = function() {
            callback(xhttp.responseText);
        };
        xhttp.onerror = function() {
            // Do whatever you want on error. Don't forget to invoke the
            // callback to clean up the communication port.
            callback('Error');
        };
        xhttp.open(method, request.url, true);
        if (method == 'POST') {
            xhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
        }
        xhttp.send(request.data);
        return true; // prevents the callback from being called too early on return
    }
});

我面临的问题是我不断收到 chrome.runtime.sendMessage 函数的错误 Invalid arguments to connect.

我不确定我错过了什么。非常感谢任何帮助我们。

您一直在尝试使用 <script> 标签将您的内容脚本注入页面。

执行此操作后,您的脚本将不再是内容脚本:它在页面上下文中执行,并失去对 Chrome API 的所有提升访问权限,包括 sendMessage.

您应该阅读 isolated world concept and this question 关于页面级脚本的内容。

要使用 jQuery,您不应依赖页面提供的副本 - 它在另一个上下文中,因此无法使用。您需要在文件中包含 jQuery 的本地副本,并在脚本之前加载它:

  1. 如果您使用清单注入脚本,您可以将 jQuery 添加到列表 之前 您的脚本:

    "content_scripts": [
      {
        matches: ["http://*.example.com/*"],
        js: ["jquery.js", "content.js"]
      }
    ],
    
  2. 如果您使用编程注入,链式加载您的脚本以确保加载顺序:

    chrome.tabs.executeScript(tabId, {file: "jquery.js"}, function() {
      chrome.tabs.executeScript(tabId, {file: "content.js"});
    });