script of preloading page message fails

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.


Solution based on the article https://developers.google.com/chrome/whitepapers/pagevisibility. I run content-script code if document.webkitVisibilityState is not 'hidden' or 'prerender', elsewhere I listen for 'webkitvisibilitychange' and wait for document.webkitVisibilityState is not 'hidden' or 'prerender'. I think check for 'prerender' is enough, but when I open a new empty tab it loads page with document.webkitVisibilityState='hidden' and this page also did not receive background messages.

function isDocumentReady() {
  return document.webkitVisibilityState != "hidden" && document.webkitVisibilityState != "prerender";
}

if (isDocumentReady())
  main();
else {

  function onVisibilityChange() {
    if (!isDocumentReady())
      return;
    document.removeEventListener(
      "webkitvisibilitychange",
      onVisibilityChange,
      false);
    main();
  }

  document.addEventListener(
    "webkitvisibilitychange",
    onVisibilityChange,
    false);

}
链接地址: http://www.djcxy.com/p/63716.html

上一篇: Chrome扩展程序:消息传递

下一篇: 预加载页面消息的脚本失败