打开或激活选项卡时自动获取 localStorage 值

get localStorage value automatically when a tab is open or activated

我需要在 tags.php 上设置一个 localStorage 项,并在用户切换到 index.php 时自动获取其更新值。

tags.php

$(document).on('click', '.tagdown', function() {
    var a = $('#tagsup').html();
    localStorage.setItem('tags', a);
});

index.php
我需要这样的东西:

$(window).onfocus(function(){
console.log(localStorage.getItem('tags'));
});

但是 $(window).onfocus() - 不存在。

我试过 body.onfocus 如果 body-child 元素有焦点,它不起作用。

任何帮助。

应该是focus而不是onfocus:

$(window).focus(function(){
    console.log(localStorage.getItem('tags'));
});

您可以使用 focus() 事件,例如:

$(function() {
    $(window).focus(function() {
        console.log('Window is in focus');
        console.log(localStorage.getItem('tags'));
    });
});

您也可以使用 on 并专注于 window,而不是 onfocus。 on 也适用于动态创建的元素。

jQuery(window).on('focus',  function(e){
        console.log("focused on " + $(e.target));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

Click anywhere in the window