Global variable in safari extension
How can I get a global variable in the safari extension that can be injected from the injected script and can be saved for the next run after the safari is closed.
and by global I mean static.
so that all injected script access the same version of that variable, not every injected script has its own.
and don't like localStorage which is domain specific .
source to share
The Safari Extension Settings API might be best used for this. This works similarly to localStorage and is available via safari.extension.settings
.
However, this is not directly accessible from injected scripts, so you must use messages to transfer data from the global page .
Something like this in the injected script:
safari.self.addEventListener('message', handleMessage, false);
safari.self.tab.dispatchMessage('getSetting', 'myVar');
function handleMessage(msg) {
if (msg.name === 'returnSetting') {
var setting = msg.message;
}
}
And on your global page:
safari.application.addEventListener('message', handleMessage, false);
function handleMessage(msg) {
if (msg.name === 'getSetting') {
var setting = safari.extension.settings(msg.message);
safari.application.activeBrowserWindow.activeTab.page.dispatchMessage('returnSetting', setting);
}
}
Alternatively, you can do more or less the same with localStorage on the global page domain, so it is not limited to single domain web pages.
source to share