google-chrome-extension - 除非单击图标,否则 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 并将其注入活动页面。
解决方案
runtime.onMessage 仅在发送消息时调用,您需要的是runtime.onStartup,它会在 Chrome 启动时调用。您还需要将 background.js 添加到 manifest.json 中的后台脚本中。
推荐阅读
- sql - 计算两个节点之间的边网方向
- php - 如何在 wordpress 中以编程方式显示自定义帖子类型的图像缩略图。?
- sql - 即使没有 INSERT 发生,序列也会递增
- excel - 如何按部分名称获取 ColumnNames 列表?
- javascript - 如何纠正 ObjectUnsubscribedError
- firebase - 用户扫描二维码以读取和写入特定数据库节点后如何在 Firebase 中设置安全规则
- python - Python和Excel:将列表作为列(特定列和行)附加到现有的excel中
- python - 在迭代器未完全耗尽时获取 StopIteration 异常
- r - 在 str_replace 中使用 ascii
- parsing - 获取响应时出现 Groovy 错误:groovyx.net.http.HTTPBuilder handleResponse WARNING: Error parsing 'text/html' response groovy.json.JsonException