javascript - 获取 "Unchecked runtime.lastError: Could not establish connection. Receiving end does not exist"但监听器存在

标签 javascript google-chrome-extension

所以我尝试从 background.js 脚本向内容脚本发送消息,但我收到此错误 Unchecked runtime.lastError: Could not establish connection。接收端不存在.

背景.js

chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
    chrome.tabs.sendMessage(tabs[0].id, {data: {
        message: 'createProfileFrame',
        userData: userData
    }}, function(res) {
        console.log(res);
    });
})

popup.js(内容脚本)

const framesContainer = document.getElementById('framesContainer');

chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
    console.log(request);
    sendResponse(true);
    if (request.data.message == 'createProfileFrame') {
        const li = document.createElement('li');
        li.style.display = 'block';

        const frame = document.createElement('div');
        frame.style.backgroundColor = 'white',
        frame.style.borderRadius = '20px';
        frame.style.width = '90%';
        frame.style.height = '3rem';
        li.appendChild(frame);
        
        framesContainer.appendChild(li);
    }
})

弹出窗口

<!DOCTYPE html>

<html>
    <head>
        <link rel="stylesheet" href="popup.css">
    </head>
    <body>
        <div class="container">
            <ul id="framesContainer"></ul>
        </div>
        <script src="popup.js"></script>
    </body>
</html>

list .json

{
    "name": "Extension",
    "description": "Test extension",
    "version": "1.0",
    "manifest_version": 3,
    "background": {
        "service_worker": "background.js"
    },
    "permissions": [
        "storage",
        "activeTab",
        "scripting",
        "cookies",
        "webRequest"
    ],
    "action": {
        "default_popup": "popup.html"
    },
    "host_permissions": ["<all_urls>"]
}

我多次阅读文档,对我来说似乎一切都是正确的,所以我不知道我做错了什么,我将不胜感激任何帮助。

最佳答案

问题是对 sendMessage() 的调用是在内容脚本的监听器加载之前完成的,向调用添加超时解决了这个问题。

关于javascript - 获取 "Unchecked runtime.lastError: Could not establish connection. Receiving end does not exist"但监听器存在,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72069730/

相关文章:

javascript - 在 JavaScript 中使用函数的最佳实践是什么

javascript - 如何使子元素粘在父底部而忽略顶部溢出?

google-chrome-extension - Chrome 扩展程序,onbeforerequest,哪个页面正在调用?

javascript - 从弹出窗口发送消息后未收到后台响应

javascript - Chrome 扩展——将 popup.js 中的数组传递到注入(inject)的 javascript 文件中

Javascript 对象属性作为 map 的键

javascript - 我如何在 Vimperator 中获取 ElementByID?

javascript - Foreach 在 foreach 中,结果为空,可能是因为异步调用

javascript - Uncaught TypeError : this. remove 不是 <anonymous>:12:14 的函数

javascript - 如何在每个复选框后获得四个以下文本输入?