Search code examples
javascriptgoogle-chrome-extension

Getting "Unchecked runtime.lastError: Could not establish connection. Receiving end does not exist" but listener exists


So i am trying to send a message from the background.js script to a content script but i get this error Unchecked runtime.lastError: Could not establish connection. Receiving end does not exist.

background.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 (content script)

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

popup.html

<!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>

manifest.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>"]
}

I read the documentation multiple times and to me it looks like everything correct so i don't know what i am doing wrong, i would appreciate any help.


Solution

  • The problem was that the call to sendMessage() was being done before the listener of the content script could load, adding a timeout to the call fixed the issue.