• 微信、钉钉、浏览器上H5页面头部标题(title)的修改,不刷新问题


    微信

    问题分析:
    主要是因为微信在首次加载页面初始化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("我的")
    
     

     
     
  • 相关阅读:
    读取exec返回值
    List
    面向对象设计原则
    CascadingDropDown省市县无刷新联动
    读写配置文件app.config
    变向实现动态水晶报表
    JS验证是否日期格式
    C#中调用API(转)
    (转自老赵Jeffrey Zhao)The status code returned from the server was: 12031”。(转)
    利用Javascript的“函数重载”实现自定义Alert样式
  • 原文地址:https://www.cnblogs.com/onesea/p/13535989.html
Copyright © 2020-2023  润新知