我正在创建一个带有content-script.js
、 abackground.js
和 a的 Chrome 扩展程序popup.html
。它对可编辑区域(如#textarea
.
为了在content-script.js
和之间进行通信background.js
,我正在使用chrome.runtime.sendMessage(message)
,并在 上运行分析background.js
并将结果保存到window.text
。如果有负面情绪,我会向页面发送一条消息以显示停车标志的图像。
然后在popup.html
(这实际上是一个.vue
文件)上,所以
mounted(){
this.bgpage = chrome.extension.getBackgroundPage()
this.text = this.bgpage.text
}
并{{text}}
在模板中显示。
它工作得很好。但我不喜欢用户必须单击按钮browser_action
才能与弹出窗口互动。
所以我将此侦听器和函数添加到content-script.js
:
document.addEventListener("click", clickStop)
function clickStop(event) {
let target = event.target.getAttribute('id');
if (target == "stop"){
let message = {
stop: true
}
chrome.runtime.sendMessage(message)
}
这对background.js
function receiver(request) {
if (request.stop == true){
window.open("popup.html", "default_title", "width=375,height=600,titlebar=no,scrollbars=yes,resizable=no,top=0,left=0");
}
这也有效。现在,当用户单击停车标志时,我会弹出一个窗口。
问题是新的弹出窗口似乎无法访问chrome.extension.getBackgroundPage()
,这意味着{{text}}
不会显示 ,就像用户单击实际browser_action
按钮时那样。(chrome.runtime.getBackgroundPage()
由于某种原因使一切崩溃。)
我已将背景权限添加到manifest.json
:
"permissions": [
"activeTab",
"<all_urls>",
"*://*/*",
"tabs",
"background"
],
"background": {
"scripts": ["js/background.js"],
"persistent" : true
},
"browser_action": {
"default_popup": "popup.html",
"default_title": "default_popup",
"default_icon": {
"19": "icons/stopsign.png",
"38": "icons/stopsign.png"
}
基本上我试图弄清楚如何让文字新弹出窗口像browser_action
.