vue meta动态设置H5里title标签内容 兼容IOS 钉钉 微信

1,204 阅读1分钟

1.在H5中同一页面动态设置meta 里面的title属性

第一步:根据vue-router里面的beforeEnter属性动态设置

{
    path: "/collection",
    name: "collection",
    beforeEnter: (to, from, next) => {
      if (to.query.code == "1004") {
        to.meta.title = "标题一";
      } else if (to.query.code == "1002") {
        to.meta.title = "标题二";
      } else if (to.query.code == "1003") {
        to.meta.title = "标题三";
      } else if (to.query.code == "1005") {
        to.meta.title = "标题四";
      } else if (to.query.code == "1006") {
        to.meta.title = "标题五";
      }
      next();
    },
    component: () => import("@/pages/collection/index.vue"),
  },

第二步:在入口文件中设置document.title = to.meta.title 动态的更改header的标题

router.beforeEach((to, from, next) => {
      if (to.meta.title) {
          document.title = to.meta.title
      }
      next()
 })

但是此方法在IOS系统下失效:主要是因为微信在首次加载页面初始化title后,就再也不监听 document.title的change事件。

解决问题:

//解决方式:给页面加上一个内容为空的iframe,随后立即删除这个iframe,这时候会刷新title。
const setDocumentTitle = function (title) {
  var _body = document.getElementsByTagName("body")[0];
  document.title = title;
  var _iframe = document.createElement("iframe");
  _iframe.src = "/favicon.ico";
  _iframe.style.display = "none";

  _iframe.onload = function () {
    setTimeout(function () {
      _iframe.remove();
    }, 0);
  };
  document.body.appendChild(_iframe);
};

判断当前设备是IOS 还是安卓

var isiOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/); //ios终端
if (isiOS) {
    setDocumentTitle(to.meta.title);
  }else{
      window.document.title = to.meta.title;
  }

钉钉内 一样还是修改不了title标题 分析原因:主要是因为在首次加载页面初始化title后,就再也不监听 document.title的change事件。 钉钉开发者工具 提供了修改title的参考:

router.beforeResolve((to, from, next) => {
  var u = navigator.userAgent;
  var isiOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/); //ios终端
  const ua = navigator.userAgent.toLowerCase();
  if (ua.match(/DingTalk/i) == "dingtalk") {
  //钉钉内打开
    dd.biz.navigation.setTitle({
      title: to.meta.title,
      onSuccess: (result) => {
        // alert(result);
      },
      onFail: (err) => {
        // alert(result);
      },
    });
  } else if (isiOS) {
    setDocumentTitle(to.meta.title);
  }
  window.document.title = to.meta.title;

  next();
});

总结:完美的解决meta标签下title的动态设置