Something strange happens in the Chrome extension.
Content script:
console.log('content');
chrome.extension.onRequest.addListener(function(request, sender, sendResponse){
console.log('request received');
sendResponse();
});
chrome.extension.sendRequest( JSON.stringify({'msg': 'page_loaded'}) );
It is just listens for extension messaging and sends the message to the background when page loaded.
Background script:
console.log('bg');
chrome.extension.onRequest.addListener(function(request, sender, sendResponse){
sendResponse();
chrome.tabs.sendRequest(
sender.tab.id,
JSON.stringify({'msg': 'page_loaded_bg_receive'}),
function(){
console.log('sendRequest page_loaded_bg_receive callback');
});
});
It is listens for messages and sends message to the sender tab.
And it seems to be working, at least in most cases in the page log appears 'request received'.
While url entering Chrome sometimes loads typed address before user hits 'enter'. And that's a strange behavior: page loading, content-script runs, sends the message to the background, but when the background sends the message back — it fails with the background log message:
Port error: Could not establish connection. Receiving end does not exist. miscellaneous_bindings:184 chromeHidden.Port.dispatchOnDisconnect miscellaneous_bindings:184
Is this a Chrome bug? What to do to send message to the preloading tab?
This is the arfificial minimal sample to reproduce such behavior. I need to call 'chrome.tabs.sendRequest' after the handling the message and more than once, so calling the 'sendResponse' is not the solution.
JSON.stringifyandJSON.parse, Chrome automatically (de)serializes requests over the channel.