0

When I am develope a chrome extension, the background shows this error:

Unchecked runtime.lastError: Could not establish connection. Receiving end does not exist.

I have read the question, but it using the chrome long-term connection, and now I am using the short connection. this is my code recieve message:

chrome.runtime.onMessage.addListener((msg, sender, sendResponse) => {
    if (sender.tab && sender.tab.active) {
        if (msg.text === 'setPageRSS') {
            handleRSS(msg.feeds, sender.tab.id);
        } else if (msg.text === 'addPageRSS') {
            addPageRSS(msg.feed, sender.tab.id);
        }
    }
    if (msg.text === 'getAllRSS') {
        sendResponse(getAllRSS(msg.tabId));
    }
});

what should I do to fix it? how to check the error? is it possible to check the recieve end exists before send message?

enter image description here

this is the popup page with sendMessage:

import '../../css/popup.less';
import ClipboardJS from 'clipboard';
import { getConfig } from '../common/config';
import { subChannel } from '../common/cruise';
import settingIcon from '../../svg/setting.svg';
import aboutIcon from '../../svg/about.svg';
import MD5 from 'md5.js';
import { Message } from 'element-ui';
let config;

function generateList(type, list) {
    let result = '';
    if (list && list.length) {
        list.forEach((item) => {
            const replaced_url = item.url.replace('{rsshubDomain}', config.rsshubDomain);
            const url = encodeURI(
                type !== 'page-rsshub' || !config.rsshubAccessControl.enabled
                    ? replaced_url
                    : config.rsshubAccessControl.useCode
                    ? `${replaced_url}?code=${new MD5().update(item.path + config.rsshubAccessControl.accessKey).digest('hex')}`
                    : `${replaced_url}?key=${config.rsshubAccessControl.accessKey}`
            );
            result += `
            <li class="rss-item">
                <img class="rss-image" src="${item.image || './rsshub.png'}">
                <a href="${url}" class="rss-info">
                    <div class="rss-title">${item.title}</div>
                    <div class="rss-url">${url.replace('https://', '').replace('http://', '')}</div>
                </a>
                ${
                    item.isDocs
                        ? `<a href="${url}" class="rss-action">文档</a>`
                        : `<div class="rss-action rss-copy" data-clipboard-text="${url}">复制</div>`
                } 
                ${
                    config.submitto.feedly ? `<input id="${url}" url="${encodeURI(url)}" type="submit" value="订阅" class="rss-action rss-submitto-feedly"></input>` : ''
                }       
            </li>
            `;
            chrome.storage.local.get("cruiseSubList", function(result){
                var isSub = false;
                var subList = result.cruiseSubList;
                subList.forEach(item=>{
                    if(item.subUrl == url){
                        isSub = true;
                    }
                });
                console.log(isSub);
                if(isSub){
                    document.querySelectorAll('input').forEach((ele) => {
                        if(ele.id == url){
                            ele.setAttribute('value','已订阅');
                        }
                    });
                }
            })
        });
        document.querySelector(`.${type} ul`).innerHTML = result;
        document.querySelector(`.${type}`).style.display = 'block';
        document.body.classList.add('something');
        
    }
}

document.querySelector('.icons-setting').innerHTML = settingIcon;
document.querySelector('.icons-about').innerHTML = aboutIcon;

chrome.tabs.query(
    {
        active: true,
        currentWindow: true,
    },
    (tabs) => {
        const tabId = tabs[0].id;

        getConfig((conf) => {
            config = conf;
            chrome.runtime.sendMessage(
                null,
                {
                    text: 'getAllRSS',
                    tabId: tabId,
                },
                (feeds) => {
                    generateList('page-rss', feeds.pageRSS);
                    generateList('page-rsshub', feeds.pageRSSHub);
                    generateList('website-rsshub', feeds.websiteRSSHub);

                    const clipboard = new ClipboardJS('.rss-copy');
                    clipboard.on('success', function (e) {
                        e.trigger.innerHTML = '已复制';
                        setTimeout(() => {
                            e.trigger.innerHTML = '复制';
                        }, 1000);
                    });

                    document.querySelectorAll('.rss-image').forEach((ele) => {
                        ele.addEventListener('error', function () {
                            this.setAttribute('src', './rsshub.png');
                        });
                    });

                    // handle a label click event
                    document.querySelectorAll('a').forEach((ele) => {
                        ele.addEventListener('click', (e) => {
                            e.preventDefault();
                            chrome.tabs.create({
                                url: ele.getAttribute('href'),
                            });
                            window.close();
                        });
                    });

                    document.querySelectorAll('input').forEach((e)=>{
                        e.addEventListener('click',(innerEvent) =>{
                            innerEvent.preventDefault();
                            //subChannelTest(e);
                            
                            var subText = e.getAttribute('value');
                            if(subText === '已订阅'){
                                Message("已订阅此频道");
                                return;
                            }
                            if(subText === '处理中'){
                                Message("请求处理中...");
                                return;
                            }
                            if(subText === '订阅'){
                                e.setAttribute('value','处理中');
                                console.info("开始处理订阅...");
                                subChannel(e,0);
                            }
                        });
                    });
                }
            );
        });
    }
);

and this is my background sendMessage function:

chrome.tabs.onActivated.addListener((tab) => {
    chrome.tabs.sendMessage(
        tab.tabId,
        {
            text: 'getPageRSS',
        },
        (feeds) => {
            handleRSS(feeds, tab.tabId, true);
        }
    );
});

chrome.tabs.onUpdated.addListener((tabId, changeInfo, tab) => {
    if (changeInfo.url && tab.active) {
        chrome.tabs.sendMessage(
            tab.id,
            {
                text: 'getPageRSS',
            },
            (feeds) => {
                handleRSS(feeds, tab.id);
            }
        );
    }
});

today I found open a new url in Google Chrome still throw this error. This situation I did not know how to avoid it.

Dolphin
  • 29,069
  • 61
  • 260
  • 539
  • I am not using `chrome.runtime.connect `, it is a long connection, I only using short connection @wOxxOm – Dolphin Apr 21 '21 at 14:14
  • So you have two sendMessage. The likely culprit is the second sendMessage because the content script wasn't yet injected (and can't receive messages) when `changeInfo.url` is reported to onUpdated listener. You can reverse the direction: use sendMessage inside the content script and process the message in your onMessage listener if `sender.tab.active` is true. – wOxxOm Apr 21 '21 at 14:30
  • Open a url also throw this error. This error may not broken the main workflow. I still want to fix it. @wOxxOm – Dolphin Apr 22 '21 at 05:51
  • When I open a newtab in Google Chrome, then enter a url like `www.google.com`, after I press enter to open the home page, the Extension I write will throw the error: `Unchecked runtime.lastError: Could not establish connection. Receiving end does not exist.` @wOxxOm – Dolphin Apr 22 '21 at 06:48
  • 1
    Yes, your message arrives before the content scripts run as I explained in my comment above. – wOxxOm Apr 22 '21 at 10:32

1 Answers1

0

finally I found when the open a newtab, throw this error, I tweak code like this:

chrome.tabs.onUpdated.addListener((tabId, changeInfo, tab) => {
    if(changeInfo && changeInfo.url === 'chrome://newtab/'){
        return;
    }
    if (changeInfo.url && tab.active) {
        chrome.tabs.sendMessage(
            tab.id,
            {
                text: 'getPageRSS',
            },
            (feeds) => {
                handleRSS(feeds, tab.id);
            }
        );
    }
});

fix one of condition.

Dolphin
  • 29,069
  • 61
  • 260
  • 539