Chrome扩展程序:SendMessage问题

Gokul NK

我试图根据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功能。

我不确定我缺少什么。我们的任何帮助将不胜感激。

可汗

您一直试图将带有<script>标签的内容脚本注入页面

完成此操作后,您的脚本将不再是内容脚本:它将在页面上下文中执行,并失去对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"});
    });
    

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

Chrome扩展程序runtime.sendmessage等待响应

chrome.runtime.sendMessage在重新加载Chrome扩展程序后从内容脚本抛出异常

chrome.runtime.sendMessage在Chrome扩展程序中不起作用

Chrome扩展程序问题(清单无效)

我的Chrome扩展程序出现问题

Chrome扩展程序:无法获取背景以将sendMessage发送到内容脚本

Chrome扩展程序:从内容到后台的sendMessage从弹出窗口获取响应

sendMessage 在 Chrome 扩展中不起作用

chrome扩展程序中的目的tabid是什么?{chrome.tabs.sendMessage(整数tabId,任何消息,函数responseCallback)}

从Chrome扩展程序调用API时出现问题

Chrome扩展程序问题,更改了textarea内容

Chrome扩展程序:无法在DOM中插入HTML,权限问题

Chrome扩展程序+ angular-cli:构建后的UI问题

Chrome的AA扩展问题

Chrome扩展程序选项

Chrome扩展程序-通知

Chrome扩展程序的指标

Chrome扩展程序CaptureStream

如何解决此本地数据问题?(Chrome扩展程序,JavaScript,jQuery)

在Chrome扩展程序中加载Polymer 1.0时出现问题

在Chrome扩展程序中解决X-Frame-Options DENY问题?

Chrome扩展程序可切换标签:标签选择超时问题

如何解决将数据从网页发送到Chrome扩展程序的问题?

带有Firebase和Chrome扩展程序的Goole Auth和Facebook Auth问题

禁用缓存Chrome扩展程序

静默安装Chrome扩展程序

关闭Chrome扩展程序选项

从chrome扩展程序发布数据

Chrome扩展程序消息传递