0

我正在创建一个带有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.

4

1 回答 1

0

问题在于我没有分享的代码的一部分,因为我没有认为它是相关的,我错了。

基本上,我的 : 有两个不同chrome.runtime.sendMessage(message);的地方content-script.js:一个有if声明,receiver另一个没有。因此,每次我发送request.stop消息时,request.text都将undefined因此而window.text成为undefined

因此,它在我的browser-action弹出窗口中起作用,因为没有request.stop发送任何消息,所以window.text仍然由最后一条消息定义。

request.stop一旦我添加了第二个条件语句,在收到消息时它就不会运行。

window.text = "there is no text";

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");
}

//removed this
//window.text = request.text;

//added this - if statement
if (request.text){
  window.text = request.text;
}
}
于 2021-02-08T20:29:37.280 回答