网络前端实用应用程序接口
最编程
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
推荐阅读
-
使用前端技术创建二维码生成器应用程序接口
-
前端] 网络应用程序接口
-
横批:网络行为管理系统启发式算法应用研究、实用性分析及实施难点探讨
-
网络前端实用应用程序接口
-
.NET高级面试指南 Topic XVIII [ 介绍外观模式(Appearance Pattern),该模式提供了一个隐藏系统复杂性的简化界面 ]。- 简化复杂系统:当系统具有复杂的子系统结构时,可以使用外观模式来简化界面。提供统一界面:当客户端需要访问多个子系统时,可以使用外观模式提供统一界面。 外观模式在现代软件开发中得到广泛应用,尤其是在复杂系统中。例如 图形用户界面库:许多图形用户界面库(如 Qt、GTK+ 等)都使用外观模式来隐藏底层的复杂性,并为开发人员提供简单的界面来创建用户界面。 操作系统接口:操作系统中的系统调用和应用程序接口通常也使用外观模式来隐藏底层硬件和系统的复杂性,为应用程序提供访问系统资源的简单接口。企业应用程序:在可能涉及多个子系统的大型企业应用程序中,外观模式可用于封装这些子系统,并为客户端提供统一的使用界面。 网络框架:许多网络框架(如 ASP.NET MVC、Spring MVC 等)也使用外观模式来隐藏底层的复杂性,并为开发人员提供简单的接口来处理 HTTP 请求和响应。 集成开发环境(IDE):集成开发环境通常包含代码编辑器、编译器、调试器等多种功能。外观模式可用于封装这些功能,并为开发人员提供开发软件的简单界面。 代码示例:
-
使用网络音频应用程序接口制作音频可视化工具
-
推荐实用的5G手机网络优化测试应用:FAT App
-
全面指南:Vite和Axios在前端网络请求中的应用