我处在一个外部JavaScript文件中,该文件可以进行ajax调用并将某些数据保存到会话存储中。 JavaScript文件是从外部站点加载的,因此,我无法对其进行编辑。
我需要运行一个函数,以将保存的数据加载到会话存储中后立即使用它。加载此数据后如何触发功能?
最佳答案
也许这可以帮助您:
window.onstorage = function(e) {
console.log('The ' + e.key + ' key has been changed from ' + e.oldValue + ' to ' + e.newValue + '.');
};
更多信息here和here
因此,您可以使用(未测试)订阅会话密钥更改:
window.onstorage = function(e) {
if (
e.storageArea === sessionStorage &&
e.key === "<your_key>" &&
e.oldValue === undefined &&
e.newValue !== undefined
) {
console.log("my key is not undefined anymore")
}
};
更新:看来它不适合您。然后,您可以尝试执行以下操作(使用时间间隔检查sessionStorage是否更改):
var INTERVAL = 2000;
// Then, in your code you can check every `INTERVAL` milleconds
// if the sessionKey you need is not null
console.log("Program starts");
// You can limit your intents too
var limit = 5;
var intervalId = setInterval(function() {
console.log("Checking sessionStorage");
var test = sessionStorage.getItem("test");
if (test !== null) {
console.log("'test' is now defined: " + test);
clearInterval(intervalId);
}
if (--limit <= 0) {
console.log("'test' has not changed");
clearInterval(intervalId);
}
}, INTERVAL);
在这里测试:https://jsbin.com/tukubutoje/edit?js,console
关于javascript - session 存储为!=未定义后如何运行函数,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/44830339/