微信
问题分析:
主要是因为微信在首次加载页面初始化title后,就再也不监听 document.title的change事件。 解决思路: 给页面加上一个内容为空的iframe,随后立即删除这个iframe,这时候会刷新title。 代码: export const ChangePageTitle = (title) => { var $body = $('body'); document.title = title; var $iframe = $('<iframe style="display: none"></iframe>'); $iframe.on('load', function() { setTimeout(function() { $iframe.off('load').remove(); }, 0); }).appendTo($body); } }
钉钉
dd.ready(function() { dd.biz.navigation.setTitle({ title : val,//控制标题文本,空字符串表示显示默认文本 onSuccess : function(result) {}, onFail : function(err) {} }); });
普通浏览器
document.title = title;
兼容微信、钉钉和浏览器的万能修改title方法
//判断当前页面是在钉钉、微信还是浏览器中打开 export const userAgentObj = () => { const ua = navigator.userAgent.toLowerCase() let isWeiXin = false, isDingTalk = false, isApp = false, obj = {} if(ua.match(/DingTalk/i)=="dingtalk"){//用钉钉打开 isDingTalk = true }else if(ua.match(/MicroMessenger/i)=="micromessenger"){//用微信打开 isWeiXin = true }else{//用其他浏览器打开 isApp = true } obj.isWeiXin = isWeiXin obj.isDingTalk = isDingTalk obj.isApp = isApp localStorage.setItem("userAgentObj",JSON.stringify(obj)) return obj } //修改头部标题的函数-----兼容微信、钉钉和浏览器 export const ChangePageTitle = (title) => { let userAgentObj = JSON.parse(localStorage.getItem('userAgentObj'))||null if(userAgentObj&&userAgentObj.isDingTalk){//钉钉内 window.$dd.ready(function() { window.$dd.biz.navigation.setTitle({ title : title,//控制标题文本,空字符串表示显示默认文本 onSuccess : function(result) { }, onFail : function(err) {} }); }); }else{//微信或浏览器内 var $body = $('body'); document.title = title;//普通浏览器用这一句就可以修改了 var $iframe = $('<iframe style="display: none"></iframe>'); $iframe.on('load', function() { setTimeout(function() { $iframe.off('load').remove(); }, 0); }).appendTo($body); } } //调用函数 ChangePageTitle("我的")