浏览器选项卡存储?

Browser tab storage?

是否存在只能由创建它的页面使用的浏览器存储?

我正在制作一个 TamperMonkey 脚本来自动化我的工作。当打开来自特定域的页面时触发。然后它会在所述页面中找到特定的 link(相同的域)并在相同的选项卡中打开它。如果新打开的页面符合条件,则返回上一页(需要手动检查)。如果没有,那么它将自行关闭。

我使用 localStorage 来标记页面是否已尝试执行此检查。否则,脚本将在加载原始页面并陷入循环时重新打开 link。

只有一个选项卡 运行ning 时,脚本 运行 运行流畅。但是当我 运行 多个选项卡(都在同一个域中)时,它经常会失败。我猜每个选项卡都可以访问相同的 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.

Source