Chrome扩展程序: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 } }); 

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

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

您一直在尝试使用标记将内容脚本注入页面。

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

您应该阅读孤立的世界概念和关于页面级脚本的这个问题 。

要使用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"}); });