企业微信会自动读取网页 title, html body 内的第一段文字和第一个图片(也有一些情况会使用网页的 favicon.ico)作为分享卡片的标题,描述,和图片。
这三个元素进行修改就好
注意:图片需要分辨率在 300x300 以上,否则可能不显示
setFirstImageAndFavicon(this.shareConfig.imgUrl)
setDescription(this.shareConfig.title)
setDocumentTitle(this.shareConfig.title)
const setFirstImageAndFavicon = (faviconUrl) => {
let link = window.document.querySelector("link[rel*='icon']") || window.document.createElement('link');
link.rel = 'shortcut icon';
link.href = faviconUrl;
window.document.getElementsByTagName('head')[0].appendChild(link);
window.document.getElementById('first-image').src = faviconUrl // first-image 为网页里的第一个图片的id,可以设置为 opacity: 0; height: 0; 来不显示。
}
const setDescription = (title) => {
window.document.getElementById('first-p').html = title // first-p 为网页里的第一行文字所在标签的id,可以设置为 opacity: 0; height: 0; 来不显示。
}
// 参考链接 http://www.cnblogs.com/lihanying/p/6227192.html
const setDocumentTitle = (title) => {
document.title = title
const iframe = document.createElement('iframe')
const loadHandler = () => {
window.setTimeout(() => {
iframe.removeEventListener('load', loadHandler)
document.body.removeChild(iframe)
}, 0)
}
iframe.style.display = 'none'
iframe.setAttribute('src', '/favicon.png')
iframe.addEventListener('load', loadHandler)
document.body.appendChild(iframe)
}