Google Chrome plug-in development: Could not establish connection. Receiving end does not exist. Could not establish connection. Receiving end does not exist

Send the "start" message to the current page through the following code:

chrome.tabs.query({
    
    active: true,currentWindow: true}, tabs => {
    
    
    let tab = tabs[0];
    chrome.tabs.sendMessage(tab.id, "start");
});

Error:

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

possible reason:

The receiving end, that is to say, the target page must have chrome.runtime.onMessage to listen for messages. If "content-script" is not injected into the page, then this page cannot receive messages.

This problem will occur if your plugin has just been loaded and you use it on a page that has already loaded.

Because the page has been loaded, it has not been injected into the script. You need to refresh the page to allow the script to be injected into the page before you can send the message.

The platform does not allow articles with too little content. The following is water

sendMessage
chrome.tabs.sendMessage(integer tabId, any message, function responseCallback)
sends a message to the content script in the specified tab page, and executes an optional callback function when the response is sent back. Each content script in the specified tab of the current extension will receive the runtime.onMessage event.

parameter type
tabId integer
message any
responseCallback optional function

If you specify the responseCallback parameter, it should specify a function of the form:

function(any response) {…};
response (any)
The JSON response object emitted by the request handler. If an error occurs while connecting to the specified tab, the callback function will be called without arguments and runtime.lastError will be set to the error message.

Guess you like

Origin blog.csdn.net/m0_46555380/article/details/127314553