Question

I'm developing a safari extension. I successfully created a global page which reacts to the toolbar button press. This action opens a new tab in the active window.

My question now is: how can I access defined variables from the global page in my newly opened browser-tab which contains the content html file from the extension? Is it possible to share variables and functions like the popover does?

safari.extension.globalPage.myFunction(); does not work...

Thanks sn3ek

Was it helpful?

Solution

A content script can only communicate with the global page via message passing.

content.js

safari.self.addEventListener('message', handleMessage, false);

// Send a message to the global page
safari.self.tab.dispatchMessage('requestVariables');

// Receive a message back from the global page
function handleMessage(msg) {
    if (msg.name === 'returnVariables') {
        console.log(msg.message);
    }
}

global.js

safari.application.addEventListener('message', handleMessage, false);

// Receive a message from the injected script
function handleMessage(msg) {
    if (msg.name === 'requestVariables') {
        var message = {prop: 'val'};
        safari.application.activeBrowserWindow.activeTab.page.dispatchMessage('returnVariables', message);
    }   
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top