首页 > 解决方案 > 除非单击图标,否则 Angular 作为后台脚本将不会执行

问题描述

我已经将我的 chrome 扩展的背景设置为使用 angular。这是我的清单。

{
    "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 扩展程序,否则角度应用程序不会运行,并且来自我的内容脚本的调用会收到未定义的响应。如果我通过单击图标打开弹出窗口,然后我可以向它发送消息并且它响应很好。

有人可以告诉我如何强制我的背景角度代码运行吗?我对 chrome 扩展相当陌生,并且无法在网上找到任何有用的东西。

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

标签: google-chrome-extensionangular6browser-action

解决方案


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


推荐阅读