IT博客汇
  • 首页
  • 精华
  • 技术
  • 设计
  • 资讯
  • 扯淡
  • 权利声明
  • 登录 注册

    微信SPA单页面应用更换title

    轩枫发表于 2016-04-09 16:21:51
    love 0

    前言

    SPA单页面应用在切换hash的时候,往往要更改页面标题,一般是通过document.title来设置。

    // eg.1
    document.title='new title'
    
    //eg.2
    document.getElementsByTagName('title')[0].innerHTML =  'new title'

    以上方式在Android生效,但在IOS中是无法在页面不刷新时设置浏览器title的。

    Hack

    //基于jQuery或Zepto
    function change_title(title){
    	document.title = title;
    	// hack在微信等webview中无法修改document.title的情况
    	var $iframe = $('<iframe src="/favicon.ico"></iframe>');
    	$iframe.on('load',function() {
    	    setTimeout(function() {
    	        $iframe.off('load').remove();
    	    }, 0);
    	}).appendTo($('body'));
    }
    
    $('#demo1').on('click', function(){
    	change_title('demo1 title');
    });
    
    
    // 原生触发
    function changeTitle(title){
    	var body = document.getElementsByTagName('body')[0];
    	document.title = title;
    	var iframe = document.createElement("iframe");
    	iframe.setAttribute("src", "/favicon.ico");
    
    	iframe.addEventListener('load', function() {
    		setTimeout(function() {
    			iframe.removeEventListener('load');
    			document.body.removeChild(iframe);
    		}, 0);
    	});
    	document.body.appendChild(iframe);
    }
    
    document.getElementById('demo2').ontouchend = function(){
    	changeTitle('demo2 title');
    }

    Demo

    http://www.xuanfengge.com/demo/201604/wx_change_title.html



沪ICP备19023445号-2号
友情链接