公司需要在使用uniapp创建的h5项目中使用动态的TDK,且源代码中不要对应的标签,需要在检查中看到且放在对应的位置。
一、我们知道uniapp,如果我们正常设置DK并不是动态的,而动态的T,
我们可以再的pages.json中设置对应的数据,例
设置对应的navigationBarTitleText即可,
但是title标签的位置并不太理想
我们可以使用uniapp官方所提供的方法在我们对应的模版页面 例我的template.html,需设置如下
<title><%= htmlWebpackPlugin.options.title %></title>
此时生成的页面中的title 就放在我们想要的位置上
二、我们知道uniapp框架是单页面应用,所以我们如果想设置DK那么需要直接在模版html上直接写,但是只是静态的,它的所有页面查看都是相同的DK。,如果你们公司不需要动态,直接写在模版html上即可
如果我们想设置动态的TDK,且不需要要源代码上展示对应标签,目前未在uniapp找到相应的api设置,目前只能采用笨方法去设置,例我再utils.js文件中声明一个方法,然后在页面之中引入此放在,再在onload方法中调用。
下面的函数是我们项目部分页面不需要DK,部分页面使用同样的DK,关于为什么这里在设置title,是因为uniapp默认会生成title标签,且我如果不写<title><%= htmlWebpackPlugin.options.title %></title>,那么title标签的位置并不是我想要的位置,我这里想要的这三个标签在一起,且在我想要设置的位置,最终效果如下图所示
title:为你需要设置的title
type:为类型,=1时为自定义设置DK,=2为固定的DK
keywords:为网站的关键词
description:为网站的描述
function setTdk(title, type=1, keywords='',description='') {
let meta = document.getElementsByTagName('meta')[1]
if (document.getElementsByTagName('title')[0] && document.getElementsByTagName('title')[0].nextSibling.type == 'text/css') {//判断页面是否存在自动生成的title,且位置是否在我预期的位置
document.getElementsByTagName('title')[0].remove()
const pageTitle = document.createElement('title');
pageTitle.innerText = title
document.head.insertBefore(pageTitle, meta)
} else {
console.log(document.getElementsByTagName('title'));
document.getElementsByTagName('title')[0].innerText=title
}
if (type == 2) {//这里设置通用的DK,避免重复传参
keywords = 'csgo开箱网,csgo开箱,csgo开箱模拟器,csgo开箱网站,csgo开箱模拟,csgo开箱多少钱'
description='gogo开箱网csgo开箱子网站的靠谱平台;正规csgo开箱一次多少钱?csgo饰品盲盒免费开箱;csgo开箱模拟器网站公平性平台'
}
if (document.getElementsByName('keywords')[0]==undefined) {//如果页面不存在DK,则需要插入对应的标签
const metaKey = document.createElement('meta');
const metaDesc = document.createElement('meta');
metaKey.setAttribute('name', 'keywords');
metaKey.setAttribute('content', keywords);
metaDesc.setAttribute('name', 'description');
metaDesc.setAttribute('content', description);
document.head.insertBefore(metaKey, meta)
document.head.insertBefore(metaDesc,meta)
} else {//如果存在,只需要修改content属性值即可
document.getElementsByName('keywords')[0].content=keywords
document.getElementsByName('description')[0].content=description
}
}
最后如下效果
至此结束,以上皆为个人的见解,有不足之处恳请各位大佬指出