-1

I'm trying to pass a variable from the settings in my safari extension to the injected javascript. I've managed to get the message passed but have no idea how to use the variable out of the handleMessage scope so I can use it in my injected file. The variable printerNAME in the handleMessage function appears not to be accessible outside of the function?

global.html

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

function handleMessage(msg) {
    if(msg.name === 'printerName') {
        alert(msg.message);
    }
    var printerName = safari.extension.settings.printerName;
    safari.application.activeBrowserWindow.activeTab.page.dispatchMessage('printerName', printerName);
}

injected.js

var printerNAME;

function handleMessage(msg) {
    if(msg.name === 'printerName') {
        printerNAME = msg.message;
    }
}

if (window.top === window) {
    safari.self.addEventListener('message', handleMessage, false);
    safari.self.tab.dispatchMessage('printerName', printerNAME);

    alert(printerNAME);
}
mousebat
  • 350
  • 2
  • 23

1 Answers1

0

Message passing is asynchronous. That means that as soon as the injected script sends off a message to the global page, it continues with the next line of code without waiting for the response (if any). Therefore, any code that depends on the response must execute only after the response is received. So, your alert(printerNAME) statement should go inside the handleMessage function.

chulster
  • 2,789
  • 13
  • 13