简体   繁体   English

safari扩展中的全局变量

[英]Global Variable in safari extension

How can i have a global variable in safari extension that can be acceded from injected script, and can be saved for the next launch after safari is closed. 我如何在safari扩展中有一个可以从注入的脚本中加入的全局变量,并且可以在safari关闭后保存以供下次启动。

and by global i mean static. 而全球我的意思是静态。
so that all injected script access the same version of that variable not every injected script has it's own. 这样所有注入的脚本都可以访问该变量的相同版本,而不是每个注入的脚本都拥有它。
and not like localStorage that is per domain. 而不是像每个域的localStorage

The Safari extension settings API might be the best thing to use for this. Safari扩展设置API可能是最好的用途。 This works similarly to localStorage and is accessible via safari.extension.settings . 这与localStorage类似,可以通过safari.extension.settings访问。

However, this isn't accessible directly from injected scripts, so you have to use messages to pass data from a global page . 但是,这不能直接从注入的脚本访问,因此您必须使用消息从全局页面传递数据

Something like this in your 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 in 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 could do more or less the same thing with localStorage within the domain of the global page, so it isn't restricted to web pages of one domain. 或者,您可以在全局页面的域内使用localStorage执行或多或少相同的操作,因此它不限于一个域的网页。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM