是否存在只能由创建它的页面使用的浏览器存储空间?
我正在制作一个 TamperMonkey 脚本来自动化我的工作。当打开来自特定域的页面时触发。然后它会在所述页面中找到特定链接(相同域)并在同一选项卡中打开它。如果新打开的页面符合条件,则返回上一页(需要手动检查)。如果没有,那么它将自行关闭。
我使用 localStorage 来标记页面是否已尝试执行此检查。否则,脚本会在加载原始页面并陷入循环时重新打开链接。
当只有一个选项卡运行时,脚本运行平稳。但是当我运行多个选项卡(都在同一个域中)时,它经常会失败。我猜每个选项卡都可以访问相同的 localStorage,从而扰乱了循环检查。无论如何,我还没有找到通过相同脚本为每个选项卡的 localStorage 指定唯一名称的方法。
因此,我需要一个浏览器存储,即使在同一个域中打开一个新的 url 之后,一个选项卡也可以使用它,但不能被另一个具有相同域的选项卡使用。
最佳答案
您可以使用 Window.sessionStorage为此目的。
示例
// Store in `name` in the current tab
sessionStorage.setItem('name', 'Some Name');
// Get `name` from sessionStorage
var name = sessionStorage.getItem('name');
alert(name); // Some Name
根据 MDN :
The sessionStorage property allows you to access a session Storage object for the current origin. sessionStorage is similar to Window.localStorage, the only difference is while data stored in localStorage has no expiration set, data stored in sessionStorage gets cleared when the page session ends. A page session lasts for as long as the browser is open and survives over page reloads and restores. Opening a page in a new tab or window will cause a new session to be initiated, which differs from how session cookies work.
关于javascript - 浏览器选项卡存储?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44667607/