简体   繁体   English

Chrome:无法同时使用内容脚本和后台脚本

[英]Chrome: Using both content and background scripts not working

I have a chrome extension that uses both content script and a background script. 我有一个使用内容脚本和背景脚本的chrome扩展程序。 Those scripts are also communicating with each other using chrome.runtime.sendMessage . 这些脚本还使用chrome.runtime.sendMessage相互通信。

But when I add both scripts in manifest.json , only the background script seems to be working. 但是,当我在manifest.json添加两个脚本时,只有后台脚本似乎可以正常工作。 Removing the background script from the manifest solves the problem and the content script get loaded. 从清单中删除背景脚本可解决此问题,并加载内容脚本。

My manifest.json 我的manifest.json

  "manifest_version": 2,
    ...
  "permissions": [
    "contentSettings",
    "notifications", 
    "storage",
    "https://*.soundcloud.com/*",
    "https://soundcloud.com/*"
  ],
  "content_scripts": [
    {
      "matches": [
        "https://*.soundcloud.com/*",
        "https://soundcloud.com/*"
      ],
      "js": [
        "js/jquery/jquery.min.js",
        "js/arrive/arrive.min.js",
        "src/inject/inject.js"
      ]
    }
  ],
  "background": {
    "scripts": [
      "src/background/background.js"
    ],
    "persistent": false
  }
}

My injected content script (works on its own): 我注入的内容脚本(独立运行):

chrome.runtime.sendMessage(response, function(response) {
    console.log("FROM BACKGROUND: " + response);
});

My background script: 我的背景脚本:

chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
    var options = {
        type: "image",
        title: "Track now playing!",
        message: response.artist + " - " + response.title,
        imageUrl: response.artwork,
        isClickable: false
    };

    chrome.notifications.create("", options, function(e) {
        sendResponse("Notification was send!");
    });
});

I think you're having trouble matching the api for the functions. 我认为您在匹配API的功能时遇到了麻烦。 You may even want to eliminate the anonymous functions to get everything working. 您甚至可能想要消除匿名功能以使所有功能正常运行。

The first (mandatory) argument to content script's sendMessage is the message you want to send. 内容脚本的sendMessage的第一个(强制性)参数是您要发送的消息。 The next argument you're using is the callback that the message receiver will call. 您使用的下一个参数是消息接收者将调用的回调。 (And don't reuse the variable name response .) (并且不要重复使用变量名response 。)

inject.js: inject.js:

var message = {
    “artist”: “Matthias”,
    “title”: “My Song”,
    “imageUrl”: “pic.png”
};

function sendResponse(response) {
    console.log(“notificationId is: “+response);
}

chrome.runtime.sendMessage(message,sendResponse);

The api for onMessage is probably a little clearer than the message passing page. onMessage的api可能比消息传递页面更清晰。 We'll keep the anonymous function because it creates a closure. 我们将保留匿名函数,因为它会创建一个闭包。 The api for create states that the callback's argument is the notification's id, which seems like it would be a useful piece of information (otherwise, you don't need any of your callbacks). create的api指出,回调的参数是通知的ID,这似乎是一条有用的信息(否则,您不需要任何回调)。 Also the first argument is optional, so we'll remove it. 另外,第一个参数是可选的,因此我们将其删除。 It also says the first mandatory argument should be NotificationOptions , which requires a type property whose value is a TemplateType . 它还说,第一个强制参数应该是NotificationOptions ,它需要一个type属性,其值是TemplateType

background.js: background.js:

function messageListener(message,sender,sendResponse) {
    var options = {
        “type”: "image",
        “title”: "Track now playing!",
        “message”: message.artist + " - " + message.title,
        “imageUrl”: message.artwork,
        “isClickable”: false
    };

    chrome.notifications.create(options, function(notificationId) {
        sendResponse(notificationId);
    });

    return true;
}

It's still not clear why you think the content script isn't loading. 尚不清楚为什么您认为内容脚本未加载。 My assumption is you're not seeing the console.log call. 我的假设是您没有看到console.log调用。 But that could be caused by several problems, not just “content script not loading”. 但这可能是由几个问题引起的,而不仅仅是“内容脚本未加载”。 My guess is you're running into something that's mentioned only in passing in onMessage : sendResponse becomes invalid when messageListener returns, unless you return true; 我的猜测是,您遇到了仅在传递onMessage时才提到的问题: sendResponsemessageListener返回时变为无效,除非您return true; from messageListener to indicate you wish to send a response asynchronously. messageListener表示您希望异步发送响应。 Since you're sendResponse ing from the asynchronous create , you need the return true; 由于您是从异步create sendResponse ,因此需要return true; to keep the message listener active. 使消息侦听器保持活动状态。

Background Script needs permission. 后台脚本需要权限。 As docs stated, when any installed hosted app, package app or extension has " background " permission, Chrome runs(invisibly) as soon as the user logs into their computer - before the user launches Chrome. 文档所述,当任何已安装的托管应用程序,程序包应用程序或扩展程序具有“ 后台 ”权限时,只要用户登录计算机,Chrome就会(看不见)运行-在用户启动Chrome之前。 The ' background ' permission also makes Chrome continue running until user explicitly quits Chrome. 后台 ”权限还使Chrome可以继续运行,直到用户明确退出Chrome为止。

You typically use the ' background ' permission with a backgroud page, event page or a background window. 通常,您将“ background ”权限与背景页面,事件页面或背景窗口一起使用。

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM