简体   繁体   English

消息未从内容脚本发送到background.js

[英]Messages not being sent from content script to background.js

I'm trying to use a content script to inject my own JS files into a page. 我正在尝试使用内容脚本将自己的JS文件注入页面。 The way I'm trying to do this is based on the system used by a Chrome extension called dotjs, which runs a little server on your machine, and makes AJAX reuests to localhost in order to retrieve the files from that server. 我尝试这样做的方式是基于一个名为dotjs的Chrome扩展程序使用的系统,它在您的计算机上运行一个小服务器,并使AJAX对localhost进行请求,以便从该服务器检索文件。

I'm fairly certain those AJAX requests will only go through if they're sent from background.js rather than a content script, due to the Same Origin Policy. 我很确定这些AJAX请求只有在从background.js而不是内容脚本发送时才会通过,因为同源策略。 I also need to use webRequest, which again only works in a background page. 我还需要使用webRequest,它只能在后台页面中使用。 But, since I need to inject the stuff into the page itself, I need a content script. 但是,由于我需要将内容注入页面本身,我需要一个内容脚本。 So my extension works with a content script that sends messages to a background page, requesting that it do all the webRequest and AJAX that it needs. 因此,我的扩展程序使用内容脚本,该脚本将消息发送到后台页面,请求它执行所需的所有webRequest和AJAX。

The problem is, the messages don't seem to be getting received by background.js. 问题是,background.js似乎没有收到消息。 I have some console.log()s in the onRequest handler in background.js as you can see, and they're not showing up in my console. 我在background.js中的onRequest处理程序中有一些console.log()s,你可以看到它们并没有出现在我的控制台中。

manifest.json 的manifest.json

{
  "name": "dotjs",
  "version": "1.5",
  "description": "~/.js",
  "icons": { "48": "icon48.png",
            "128": "icon128.png" },
  "content_scripts": [{
    "all_frames": true,
    "run_at":     "document_start",
    "matches":    ["[censored]"],
    "js":         ["dotjs.js"]
  }],
  "background": {
    "scripts": ["jquery.js", "background.js"]
  },
  "permissions": ["tabs", "webRequest", "extension"]
}

dotjs.js dotjs.js

console.log("dotjs.js running");

var requestFilter =
    {
        url: "[censored]"
    };

var blockingResponse =
    {
        redirectUrl: "http://localhost:2262/Pigman/ips.chat.js"
    };  

function requestInterceptor(details)
{
    return blockingResponse;
}

chrome.extension.sendRequest(
    {
        type: "setListener",
        func: requestInterceptor,
        filter: requestFilter
    }
);

chrome.extension.sendRequest(
    {
        type: "loadJS",
        filename: "Elizabot/elizabot.js"
    },
    function (response) { eval(response); }
);

chrome.extension.sendRequest(
    {
        type: "loadJS",
        filename: "Elizabot/elizadata.js"
    },
    function (response) { eval(response); }
);

background.js background.js

function loadJSFile(filename)
{
    $.ajax({
        url: 'http://localhost:2262/Pigman/' + filename + '.js',
        dataType: 'text',
        success: function(d){
            return d;
        },
        error: function(){
            console.log('no file found at localhost:2262/' + filename + '.js')
        }
    });
}

chrome.extension.onRequest.addListener(
    function(request, sender, sendResponse)
    {
        console.log("background.js received request:");
        console.log(request);
        if (request.type == "setListener")
        {
            chrome.webRequest.onBeforeRequest.addListener(request.func, request.filter);
        }
        if (request.type == "loadJS")
        {
            sendResponse(loadJSFile(request.filename));
        }
    }
);

There are many flaws in your code/design: 您的代码/设计存在许多缺陷:

  1. Content scripts can make cross-origin AJAX request, provided that the resource URL is specified at the permissions section in the manifest file. 只要在清单文件的permissions部分指定了资源URL,内容脚本就可以发出跨源AJAX请求。
  2. The webRequest API does not capture any requests created within the scope of a Chrome extension. webRequest API不会捕获在Chrome扩展程序范围内创建的任何请求。
  3. The return statement in the success handler does not return the response to the caller of loadJSFile : success处理程序中的return语句不会将响应返回给loadJSFile的调用者:

      sendResponse(loadJSFile(request.filename)); ... function loadJSFile(filename) { $.ajax({ ... success: function(d){ return d; } ... 

    At least use: 至少使用:

     loadJSFile(request.filename, sendResponse); function loadJSFile(filename, sendResponse) { $.ajax({ url: 'http://localhost:2262/Pigman/' + filename + '.js', dataType: 'text', success: sendResponse, /// <--- Now it works! 

Final note on debugging: I'm pretty sure that the messages are logged in the console. 关于调试的最后注意事项:我很确定消息是在控制台中记录的。 You're just looking at the wrong place. 你只是看错了地方。 See Google chrome extension - logging from background.js for the steps to read the console output for the background page. 请参阅Google Chrome扩展程序 - 从background.js记录,以获取读取后台页面控制台输出的步骤。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 从内容脚本调用一个注入按钮到background.js - Calling an injected button from the content script to the background.js 将消息从background.js发送到内容脚本 - Sending message from background.js to content script 从background.js向内容脚本发送消息 - Sending a message from background.js to a content script Chrome扩展程序从Background.js向内容脚本发送消息 - Chrome Extension Send Message From Background.js to Content Script 在内容脚本中从background.js调用事件侦听器 - Call event listener from background.js in content script 邮件未在Chrome扩展程序中从background.js发送到main.js - Messages not getting sent from background.js to main.js in Chrome extension 将消息从 Content.js 传递到 Background.js,然后返回到 Content.js - Passing Messages From Content.js To Background.js Then Back To Content.js Chrome-扩展程序:将消息从background.js发送到content.js时出错 - Chrome - Extension: Error when sending messages from background.js to content.js Background.js找不到使用内容脚本注入的内容 - Background.js Doesn't Find Content Injected with Content Script 如何将数组从 background.js 传递给 inject.js(内容)脚本(Chrome 扩展程序) - How to pass an array from background.js to inject.js (content) script (Chrome Extension)
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM