除非单击图标,否则不会执行Angular作为背景脚本

时间:2018-08-02 10:56:04

标签: google-chrome-extension angular6 browser-action

我已将chrome扩展程序的背景设置为使用角度。这是我的清单。

{
    "manifest_version": 2,
    "name": "Canary",
    "description": "Provides a means to add shopping items to your Canary wishlists",
    "version": "1.0",
    "author": "Enlisted Innovations LLC",
    "icons": {
        "96": "/assets/icons/canary-icon.png"
    },
    "browser_action": {
        "default_title": "Canary",
        "default_popup": "index.html#/home"
    },
    "background": {
        "scripts": [
            "/main.js"
        ],
        "persistent": false
    },
    "content_scripts": [{
        "matches": ["*://*.google.com/*"],
        "js": ["content-script.js"]
    }],
    "permissions": [
        "webNavigation",
        "activeTab",
        "identity",
        "tabs",
        "activeTab",
        "http://*/*",
        "https://*/*/*"
    ],
    "content_security_policy": "script-src 'self' 'unsafe-eval' https://maxcdn.bootstrapcdn.com https://ajax.googleapis.com; object-src 'self'"
}

我在app.component.ts中为消息创建了一个侦听器,以进行测试是否有效。

import { Component, OnInit} from '@angular/core';
import { GlobalRef } from './globalref';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
  title = 'app';

  private window;

  constructor(private globalRef: GlobalRef) {
    this.window = this.globalRef.nativeGlobal.window;
    this.chromeConnect();
  }

  public ngOnInit() {
    // this.chromeConnect()
  }

  private chromeConnect() {
    const tabQueryData = { active : true, currentWindow: true };

    this.window.chrome.tabs.query(tabQueryData, (tabs) => {
        const port = window.chrome.tabs.connect(tabs[0].id);
        port.postMessage("Hello");
        port.onMessage.addListener((response) => {
          alert("Content script responded: " + response);
        });
    });

    this.window.chrome.runtime.onMessage.addListener((req, sender, sendResponse) => {
      alert("Message received");
      const response = "hello";
      sendResponse(response);
    });
  }
}

如果我包含background.js文件,例如

(function() {
    alert("testing");
    this.window.chrome.runtime.onMessage.addListener((req, sender, sendResponse) => {
        alert("Message received");
        const response = "hello";
        sendResponse(response);
      });
})()

然后,我可以使用gulp捆绑内容脚本,该脚本发送一条消息以使其可以被拦截。一切正常。

我的问题是,除非我通过单击浏览器中的图标打开chrome扩展程序,否则Angular应用程序将不会运行,并且来自内容脚本的调用会收到未定义的响应。如果我通过单击该图标打开弹出窗口,则可以向其发送消息,并且响应良好。

有人可以告诉我如何强制我的背景角度代码运行吗?我对chrome扩展程序还很陌生,还无法在线找到任何有用的信息。

如果我获得弹出html,它还会执行它后面的角度吗?如果是这样,那么我将调用getPopup并将其注入到活动页面中。

1 个答案:

答案 0 :(得分:0)

runtime.onMessage仅在发送消息时调用,您需要的是runtime.onStartup,Chrome启动时会调用它。您还需要将manifest.json中的background.js添加到后台脚本中。