views:

71

answers:

1

Hi,

I'm building a safari extension... I need to get some settings, but, messages are asynchronous, so, if I query the global page for some settings, it isn't there right away... How can I solve this??

Global page (the message is received by the injected JS script)

    <!DOCTYPE HTML>
    <html>
  <script language="javascript">
  function messageHandler(event) {
   var activeTab = event.target.browserWindow.activeTab
   if (event.name === "getSettings") {
    activeTab.page.dispatchMessage("returnedSettings", safari.extension.settings[event.message]);
   } else if(event.name === 'openNewTab') {
    safari.application.activeBrowserWindow.openTab().url = event.message;
    activeTab.page.dispatchMessage("focus");
   } else if(event.name === 'openNewVenster') {
    safari.application.openBrowserWindow().activeTab.url = event.message;
    //activeTab.page.dispatchMessage("focus");
   }
  }

  safari.application.addEventListener("message", messageHandler, false);
  </script>
 </head>
    </html>

main.js

        var oi = 'tab';
  // Message Event Handler
  function handleMessage(e) {
   if(e.name == 'returnedSettings') {
    oi = e.message;
   } else if(e.name == 'focus') {
    window.focus();
   }
  }

  // Message Event Listener
  safari.self.addEventListener('message', handleMessage, false);
  safari.self.tab.dispatchMessage('getSettings', 'open');

I need var oi in code under here... But I don't know how I can get it there, because it will be default if the code is executed, because of asynchronous messages...

A: 

You don't say much about what you're trying to do, but you're right that messages are asynchronous. If what you're doing can't be done directly in the global page, you can use the specialized canLoad message. It's kind of a hack unless, of course, you're actually checking to see whether something can load, but I've used it a few times rather effectively.

Rob Wilkerson