欢迎您访问 最编程 本站为您分享编程语言代码,编程技术文章!
您现在的位置是: 首页

网络前端实用应用程序接口

最编程 2024-03-21 10:23:39
...

MENU

  • BroadcastChannel
  • visibilitychange
  • 相关链接


BroadcastChannel

简单介绍

BroadcastChannel是一个Web API,用于在浏览器的不同窗口、标签页或者甚至不同的浏览器实例之间建立通信。它允许在同一个origin(来源)下的不同上下文之间发送数据,例如在同一个域名下的不同页面之间进行通信。


创建频道

const channel = new BroadcastChannel('id_a');

发送消息

channel.postMessage('Hello from sender!');

接收消息

channel.onmessage = function(event) {
	console.log('Received message: ', event.data);
};

关闭频道

channel.close();

接收页面

<script>
    const channel = new BroadcastChannel('id_a');

    channel.onmessage = function (event) {
        let body = document.querySelector('body');

        body.textContent = event.data;
    };
</script>

发送页面

<div>
    <input type="text" placeholder="请输入内容">
    <button onclick="handleSend()">发送消息</button>
</div>

<script>
    const channel = new BroadcastChannel('id_a');

    function handleSend() {
        let input = document.querySelector('input');

        if (input.value) channel.postMessage(input.value);
    }
</script>

visibilitychange

简单介绍

visibilitychange是一个在Web前端开发中使用的事件,它是HTML5新增的一部分,用于检测用户是否正在浏览当前页面或者切换到了其他标签页应用程序。这个事件在用户切换标签页、最小化浏览器窗口、切换到其他应用程序等情况下会被触发。
当用户切换到其他标签页或最小化浏览器窗口时,当前页面会被认为不可见,这时visibilitychange事件会被触发,从而让开发者可以在页面不可见时执行一些特定的操作,比如停止播放视频、动画或音频,减少对CPU和内存的消耗,提升用户体验。


简单示例

document.addEventListener("visibilitychange", function() {
  if (document.visibilityState === 'hidden') {
    console.log('Page is now hidden');
    // Perform actions when page is hidden
  } else {
    console.log('Page is now visible');
    // Perform actions when page is visible
  }
});

在上面的示例中,当用户切换到其他标签页时,控制台会输出"Page is now hidden",当用户切换回页面时,控制台会输出"Page is now visible"。通过监听visibilitychange事件,可以在页面状态变化时执行相应的操作,以提升用户体验。


定时器示例

function init() {
    let a = 0,
        b = undefined;

    function handleInte(para = 1) {
        b = setInterval(
            () => {
                console.log(a);
                a++;
            },
            1000 * para
        );
    }

    handleInte(2);

    document.addEventListener("visibilitychange", () => {
        let visi = document.visibilityState;

        if (visi === "visible") handleInte(2);
        if (visi === 'hidden') {
            clearInterval(b);
            b = undefined;
            a = 0;
        }
    });
}

init();

相关链接

visibilitychange、share、BroadcastChannel、Internationalization

推荐阅读