mishe / blog

前端碰上的问题或体会
230 stars 39 forks source link

用document.title=“xxx”动态修改title,在ios的微信下面不生效bug #57

Open mishe opened 8 years ago

mishe commented 8 years ago

ios的微信下面修改title不生效bug

同样是微信,安卓和ios的设置title会有非常大的区别,安卓系统的微信,只要调用document.title=“xxx”就可以轻松的改变页面的title,但ios系统不能,时好时坏的,非常不稳定;

通过百度,站在巨人的肩膀上,封装了一个简单的,针对修改微信title的工具

源码如下

$.extend($, {
    setWeixinTitle: function (title) {
        document.title = title;

        // hack在微信IOS webview中无法修改document.title的情况
        if ($.isWeixin() && $.isIOS()) {
            var $iframe = $('<iframe src="/st/images/icon144.png"></iframe>');
            $iframe.on('load', function () {
                setTimeout(function () {
                    $iframe.off('load').remove();
                }, 0);
            }).appendTo('body');
        }
    }
});

现在只要调用$.setWeixinTitle('xxxx'),就可以轻松搞定了

源码中,增加了对微信和ios系统的设别,然后通过hack方式,实现了动态更新微信ios系统的title

如果不加这个判断,会造成部分安卓系统vebview的显示问题。

wszgxa commented 8 years ago

这个方法会在history 中增加一条记录。单页面应用会出问题。

mishe commented 8 years ago

不会的,用的是iframe,并不产生hashchange

kisnows commented 8 years ago

@mishe 这样的方法会导致页面刷新。

crazyair commented 7 years ago

react 怎么写 我用了 还是不行

wszgxa commented 7 years ago

vue下面的例子

https://gist.github.com/wszgxa/48eefb02650ea011ab28a116643890a9

crazyair commented 7 years ago

有没有 react的例子

crazyair commented 7 years ago

还有 我这个不是做app 是html 这种方式都不行

kaysonli commented 7 years ago

不只是微信,其他Hybrid应用也是这样。iOS的webview里貌似只在加载页面的时候能读取到document.title,之后通过JS改的title都不更新了。安卓就没这个问题。

crazyair commented 7 years ago

这个方式可以 之前不行 是用的微信工具不可以!

fengxiqiu commented 7 years ago

ios系统微信6.5.3后,这个方法不行了,第一次进入页面改变,刷新一次页面后就可以修改。

wszgxa commented 7 years ago

那个vue例子里面核心的就这个方法啊

const iframeLoad = function (src) {
    let iframe = document.createElement('iframe')
    iframe.style.display = 'none'
    iframe.src = src
    document.body.appendChild(iframe)
    iframe.addEventListener('load', function () {
      setTimeout(function () {
        iframe.remove()
      }, 0)
    })
  }

搬到react里面很容易吧。

mishe commented 7 years ago

微信ios升级到WKWebview又失效了,https://github.com/deboyblog/vue-wechat-title/issues/2

mishe commented 7 years ago

ios 微信6.5.6版本修复了BUG,因此,之后的版本就无需hack了

Bisots commented 7 years ago

无需hack,是不是就直接用document.tilte去改?但是这样改,IOS6.5.7还是无效

yuluhuang commented 6 years ago

@wszgxa react 我在路由切换时调用 document.body.appendChild(iframe) 重复渲染变成死循环