How to trigger an event after a Chrome extension popup is displayed?

流过昼夜 提交于 2019-12-24 04:32:07

问题


I am using jQuery with a Google Chrome extension popup. The pop-up page uses jQuery's 'document.ready' event to trigger a request to a web service. The problem is that the pop-up does not render until a response is received, which makes it seem unresponsive. Here's an outline of the page:

<html>
<head>
    <script type="text/javascript" src="./plugin.js"></script>
    <script type="text/javascript">
        $(document).ready(function() {
            plugin.init();            
            plugin.getData();
        });        
    </script>
</head>
<body>...</body>
</html>

Is there an event I can use to trigger 'getData()' after Chrome renders the pop-up? I have tried monkeying with visibility events of divs within the body, but I haven't been able to trigger these events automatically other than by handling document.ready, which leads to the same behavior.


回答1:


Use setTimeout with no delay:

<html>
<head>
    <script type="text/javascript" src="./plugin.js"></script>
    <script type="text/javascript">
        $(document).ready(function() {
            plugin.init();            
            setTimeout(plugin.getData);
        });        
    </script>
</head>
<body>...</body>
</html>

I've done this in an extension of my own, and it should do the trick.




回答2:


Maybe you could interact with the background page to fetch data asynchronously:

plugin.init()

chrome.extension.sendRequest({fetch: true}, function(response) {
  plugin.handleData(response);
});

Background:

chrome.extension.onRequest.addListener(function(request, sender, sendResponse) {
  if (request.fetch){
    sendResponse(getData());
  }
});


来源:https://stackoverflow.com/questions/7139055/how-to-trigger-an-event-after-a-chrome-extension-popup-is-displayed

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!