JS动态更新微信浏览器中的title

时间:2023-03-10 04:50:02
JS动态更新微信浏览器中的title

问题:

最近在做一个微信中分享的宣传页,分不同的场景,切换不同的场景时需要设置不同的title,实现的方案很简单,当用户切换场景的时候,修改document对象的title属性,可是在实际测试中,ios微信确不起作用。

解决思路:

首先怀疑ios微信不支持,document.title修改头部修改,但是我们经过测试,如果页面首次加载直接修改title属性是可以实现的。所以这里原因有可能就是只在页面首次加载时初始化了标题title,之后就没有再监听 window.title的change事件,所以我们这里只需要想办法触发window.title的监听事件。

解决方案:

这里我们采用了hack来解决。当我们修改了title后,立即创建一个请求,加载一个空的iframe,从而触发window.title的监听。然后我们立即移除空请求,保证不会对页面造成影响。

实现代码:

<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no" />
<title>测试</title>
</head>
<body>
</body>
<script type="text/javascript">
setTimeout(function(){
setTitle('title修改了')
}, 2000); function setTitle(title){
document.title = title || document.title;
var ua = navigator.userAgent.toLowerCase();
if(ua.match(/MicroMessenger/i)=="micromessenger" && !!ua.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/i)){
var ifr = document.createElement('iframe')
ifr.src = "/favicon.ico";
ifr.onload = function() {
setTimeout(function(){
ifr.remove();
}, 0)
}
document.body.appendChild(ifr);
}
}
</script>
</html>