Add-in persistent settings in OSX/Mac

2019-05-24 13:20发布

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条回答
做自己的国王
2楼-- · 2019-05-24 13:43

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

查看更多
登录 后发表回答