javascript - 如何解决从后台脚本到另一个脚本发生的消息传递错误?

标签 javascript html google-chrome-extension frontend messaging

我正在尝试将一些选定的文本从当前页面发送到 HTML 页面。因为,我不能直接这样做,我使用消息传递:内容脚本到后台脚本,然后后台脚本到 HTML 页面。但是,如果 HTML 尚未打开,则会出现错误,即使这样我第一次也会出现错误:

background.js:1 Uncaught (in promise) Error: Could not establish connection. Receiving end does not exist.

如果我关闭页面,然后再次运行,这个错误会一直发生。

解决方案是什么?

我的代码如下:

弹窗.js

chrome.runtime.onMessage.addListener(function (request, sender, sendResponse) {
console.log("from popup = \n"+request.bg);
})  

背景.js

chrome.runtime.onMessage.addListener(function (request, sender, sendResponse) {

chrome.tabs.create({url: 'popup.html'});
chrome.runtime.sendMessage({bg: request.exc})
                                                                              })

内容.js

string=[];
function doc_keyUp(e) {
if (getSelectionText() != "")  {
if (e.key === '1') {
    string=getSelectionText();
    chrome.runtime.sendMessage({exc: string});
            
                   } 
                                }
                      } // doc_keyUp(e)
console.log('The program has started!!!');  
// register the handler 
document.addEventListener('keyup', doc_keyUp, false);                              

function getSelectionText() {
    var text = "";
     text = window.getSelection().toString();
    if (window.getSelection) {
        text = window.getSelection().toString();
    } 
    else if (document.selection && document.selection.type != "Control") {
        text = document.selection.createRange().text;
    }
    return text;    
}

popup.html

<html>
<script src="popup.js">
</script>
</html>

我这样做是为了构建一个 chrome 扩展,所以如果需要的话:

list .json

{
  "name": "",
  "version": "1.0",
  "description":"",
  "manifest_version": 3,
  "content_scripts": [
    {
      "matches": ["<all_urls>"],
      "js": ["content.js"]
    }
  ],
  "action": {
    "default_title": "T"
  },
  "background":{
    "service_worker": "background.js"
  },
  "permissions": ["tabs","storage"]
}

后脚本:

  1. 是否有其他方法可以不通过后台脚本直接将数据从内容脚本发送到 HTML 脚本(例如,这里的 popup.js 就是这样的脚本)?
  2. 是否可以在不将消息传递给任何其他脚本的情况下从后台脚本获取变量?我看到了使用 chrome.extension.getBackgroundPage() 的解决方案,但它在 manifest v3 之后不再起作用。还有什么事吗?

最佳答案

您可以使用 localStorage 来发送和获取项目。如果您的项目不包含在您的 localStorage 中,您可以对其进行初始化。

内容.js

localStorage.setItem("bg", "#000000"); // <- You can send json or whatever you want

弹出窗口

var bg = localStorage.getItem("bg");

或者您可以使用 chrome.storage接口(interface)

内容.js

chrome.storage.local.set({bg: value}, function() {
  console.log('Value is set to ' + value);
});

弹出窗口

chrome.storage.local.get(['bg'], function(result) {
  console.log('Key is ' + result.bg);
});

存储添加到权限。

并且你需要添加到你的扩展权限( list 文件 ) 但是你应该小心,因为

confidential user information should not be stored! The storage area isn't encrypted.

工作代码:

内容.js

string=[];
function doc_keyUp(e) {
    if (getSelectionText() != "")  {
        if (e.key === 'Enter') { 
            string=getSelectionText();
            chrome.storage.local.set({bg: string}, function() {
                console.log('Bg is set to ' + value);
            });
            chrome.runtime.sendMessage({});
        } 
    }
} // doc_keyUp(e)
console.log('The program has started!!!');  
    // register the handler 
document.addEventListener('keyup', doc_keyUp, false);                              
    
function getSelectionText() {
    var text = "";
    text = window.getSelection().toString();
    if (window.getSelection) {
        text = window.getSelection().toString();
    } 
    else if (document.selection && document.selection.type != "Control") {
        text = document.selection.createRange().text;
    }
    return text;    
}

弹出窗口

chrome.storage.local.get(['bg'], function(result) {
    alert('Bg is ' + result.bg);
});

背景.js

chrome.runtime.onMessage.addListener(function (request, sender, sendResponse) {
    chrome.tabs.create({url: 'popup.html'});
});

我在 content.js 中更改了 e.key === 'Enter' 以便更好地测试。我从 popup.js 中删除了 chrome.runtime.onMessage.addListener 因为你会在 background.js 收到消息后调用弹出窗口,所以你不会在 popup.js 中不需要每次都获取消息。您需要在创建弹出窗口时获取一次值。

选定的文字图片:

enter image description here

弹出提示:

enter image description here

关于javascript - 如何解决从后台脚本到另一个脚本发生的消息传递错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72679574/

相关文章:

javascript - 重新排列彼此太近的点

javascript - 如何禁用 "Leave site?. Changes you made may not be saved"以 Angular 弹出?

Javascript - 检查序列化表单是否为空

javascript - 将文本框上的用户输入限制为特定字母

google-chrome-extension - 修改关于延迟库的 dart2js 输出

javascript - 在 Chrome 扩展中使用 AngularJS

javascript - 在回调中获取上传图像的高度和宽度 -javascript

javascript - Internet Explorer 抛出 SCRIPT5022 : HierarchyRequestError when trying to appendChild an HTML object from another window

javascript - 使用chrome扩展获取网页中的所有超链接标题

javascript - 如何删除 JSON 返回 C# 中的列名称