Search code examples
javascriptsafari-extension

Safari extension - How can I get multiple pages to write to one new page? (see pic)


I'm building a safari extension that I want to take some data from a few pages and aggregate to a new blank page where it will be nicely formatted and compared.

I am able to have the pages send their data over to the global.html but as you probably know, the global.html can not write to a page even though it can open a new blank page.

Any ideas?

I could send all the data to a database but that seems so clunky to have to use the network to do something that should be completely local.

flow diagram


Solution

  • You can't modify the DOM from the global.html file. But you can send messages from your global.html to a window you opened. The window just needs code to be able to receive the message.

    So you would grab the content from the pages, message it over to global.html, then global.html would message it over to your new window.

    You can have your global.html file open a new window to an internal file in your extension folder (calling it popup.html) like so:

    var myWin = safari.application.openBrowserWindow();
    myWin.activeTab.url = safari.extension.baseURI + "popup.html";
    

    You can then message the window like so:

    myWin.activeTab.page.dispatchMessage("messageName", {some: 'data'});
    

    In your popup.html file you need some code to receive that message and you can do that like so:

    safari.self.addEventListener("message", waitForMessage, false);
    
    function waitForMessage(e){
        if(e.name == 'messageName'){
            var data = e.message;
        }
    }
    

    If you need to message back to global.html you can do that like this:

    safari.self.tab.dispatchMessage("testing",{'this': 'that'});
    

    See more about messaging in safari extensions here: https://developer.apple.com/library/content/documentation/Tools/Conceptual/SafariExtensionGuide/MessagesandProxies/MessagesandProxies.html#//apple_ref/doc/uid/TP40009977-CH14-SW1