Add-in persistent settings in OSX/Mac

痞子三分冷 提交于 2019-12-10 10:41:51

问题


I am having trouble finding a way to store persistent settings for an office.js add-in on Mac.

On windows localStorage works perfect as it saves settings that persist through closing and opening Word.

On Mac localStorage does not persist closing and opening Word, not even through a refresh or closing and opening of the add-in.

Here is a simple code sample:

var settingString = 'mySetting';
var oldValue = localStorage.getItem(settingString);
write('oldValue: "' + oldValue + '"');
var d = new Date();
var newValue = d.getHours() + ':' + d.getMinutes() + ':' + d.getSeconds();
localStorage.setItem(settingString, newValue);
write('newValue: "' + newValue + '"');

回答1:


iOS currently has a bug that's preventing us from fixing this localStorage issue yet. In the meantime, you have two potential workarounds:

Cookies

If you want the setting to be persisted across documents, use JavaScript cookies (w3schools doc) until the bug is fixed:

var settingString = 'mySetting';
var oldValue;
var myCookies = document.cookie.split(';');
for(var i = 0;i < myCookies.length;i++){
    var myCookie = myCookies[i].trim();
    if(myCookie.indexOf(settingString + "=") == 0){
        oldValue = myCookie.substring(settingString + 1,myCookie.length);
    }
}
write('oldValue: "' + oldValue + '"');
var d = new Date();
var newValue = d.getHours() + ':' + d.getMinutes() + ':' + d.getSeconds();
var expiry = d.setTime(d.getTime() + (14 * 86400000)); // # milliseconds in a day
document.cookie = settingString + "=" + newValue + "; expires=" + expiry.toGMTString();
write('newValue: "' + newValue + '"');

Settings

If it's sufficient for you to persist the value only in the current document, you can use the Office Settings API (Office.js Settings object doc):

var settingString = 'mySetting';
var oldValue = Office.context.Settings.get(settingString);
write('oldValue: "' + oldValue + '"');
var d = new Date();
var newValue = d.getHours() + ':' + d.getMinutes() + ':' + d.getSeconds();
Office.context.Settings.set(settingString, newValue);
Office.context.Settings.saveAsync(function(asyncResult){
    write('newValue: "' + newValue + '"');
});

-Michael Saunders, program manager for Office add-ins



来源:https://stackoverflow.com/questions/38716476/add-in-persistent-settings-in-osx-mac

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!