除非单击图标,否则作为背景的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);
});
})()

然后,我可以使用gump捆绑一个内容脚本,它可以发送一条消息,让它拦截。一切正常。

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

有人能告诉我如何强制运行我的背景角度代码吗?我对chrome扩展还很陌生,在网上找不到任何有用的东西。

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

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

最新更新