Chrome扩展程序:与SendMessage问题 [英] Chrome Extension : Issue with SendMessage

查看:514
本文介绍了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({
方法:'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 ();
var method = request.method?request.method.toUpperCase():'GET';
xhttp。 onload = function(){
callback(xhttp.responseText);
};
xhttp.onerror = function(){
//做任何你想做的事情, t忘记调用
//回调来清理通信端口
callback('Error');
};
xhttp.open(method,request.url, true);
if(method =='POST'){
xhttp.setRequestHeader('Content-Type','application / x-www-form-urlencoded');
}
xhttp.send(request.data);
返回true; //防止ca在返回
}
});

我遇到的问题是我不断收到错误连接无效的参数。 for chrome.runtime.sendMessage 函数。



我不确定我我错过了。任何帮助我们都将不胜感激。

解决方案

您一直在尝试使用<$ c $注入内容脚本到页面当你这样做的时候,你的脚本不再是一个内容脚本:它执行在脚本的上下文中并且失去了对Chrome API的所有提升访问权限,包括 sendMessage



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



要使用jQuery,您不应该依赖页面提供的副本 - 它位于另一个上下文中,因此无法使用。您需要在文件中包含jQuery的本地副本,并将其加载到脚本之前: 如果您使用显示为注入脚本,您可以在脚本之前将添加到列表中:

 content_scripts :[
{
匹配:[http://*.example.com/*],
js:[jquery.js,content.js]


code $如果您使用的是编程式注入,加载您的脚本以确保加载顺序:

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



I am trying to change the contents of a page based on the output of a xhr call. I am sending a message from content.js making the xrh call in the background js file and then passing the output to content.js which alters the content of the page.

From my content.js file I am doing the following.

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

In my main.js I am doing

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

And in my bg.js I have the following

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

The issue I am facing is I keep getting the error Invalid arguments to connect. for chrome.runtime.sendMessage function.

I am not sure what I am missing. Any help us is greatly appreciated.

解决方案

You have been trying to inject your content script into the page with a <script> tag.

When you do it, your script ceases to be a content script: it executes in the context of the page, and loses all elevated access to Chrome API, including sendMessage.

You should read up on isolated world concept and this question about page-level scripts.

To use jQuery, you should not rely on the copy provided by the page - it's in another context and therefore unusable. You need to include a local copy of jQuery with your files and load it before your script:

  1. If you're using the manifest to inject scripts, you can add jQuery to the list before your script:

    "content_scripts": [
      {
        matches: ["http://*.example.com/*"],
        js: ["jquery.js", "content.js"]
      }
    ],
    

  2. If you are using programmatic injection, chain-load your scripts to ensure the load order:

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

这篇关于Chrome扩展程序:与SendMessage问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆