这是使用存储API为数据填充多个选项卡的正确方法吗?

时间:2017-02-02 01:46:10

标签: javascript local-storage session-storage web-storage

我实际上是在尝试使用Web Storage API在多个标签页中传播数据。举个例子,这就是我的意思here

我的行为如下 - 在页面加载时,我看到从会话存储中检索到并保存在localStorage中的信息。

但是,当我将URL复制并粘贴到新窗口时,我没有将链接添加到页面中,而是出现此错误:

Uncaught TypeError: Cannot read property 'profile' of null
    at populateStorage (dashboard:464)
    at setValue (dashboard:469)
    at dashboard:482
    at dashboard:487

这是我的代码:

(function() {

    function getSessionStorage() {
        try {
            if (!!window.sessionStorage) return window.sessionStorage;
        } catch (e) {
            return e.error;
        }
    }

    function getLocalStorage() {
        try {
            if (!!window.localStorage) return window.localStorage;
        } catch (e) {
            return e.error;
        }
    }

    function populateStorage() {
        var string = String.prototype.toString.call(obj.profile.data.vanityName);
        local_storage.setItem('vanityName', string);
    }

    function setValue() {
        populateStorage();
        var val = local_storage.getItem('vanityName');
        return val;
    }

    var session_storage = getSessionStorage(),
        local_storage = getLocalStorage(),
        rep_info = document.getElementById('rep-info'),
        session = session_storage.getItem('ngStorage-getRepInfo'),
        obj = JSON.parse(session),
        your_avon_URL = 'https://youravon.com/';


    rep_info.insertAdjacentHTML('afterbegin', '<a href="' + your_avon_URL + (setValue()) + '">youravon.com/' + (setValue()) + '</a>');

})();

这不是正确的方法吗?从会话存储中提取,然后保存到localStorage,以便在将链接复制并粘贴到新选项卡时保留?

提前致谢!

0 个答案:

没有答案