因为微信公众号文章具有防盗链,所以不能直接用iframe内嵌显示文章内容。下面是解决问题的步骤
1、请求链接,获取整个html
//微信公众号文章内容
getWeixinContent(URL:any){
let http = (window.location.protocol === 'http:' ? 'http:' : 'https:');
let realurl = http + '//cors-anywhere.herokuapp.com/' + URL;
if (this.tool.deviceType()) {//判断是原生还是web,原生走httpApp,web走axios
return new Promise((resove, reject) => {
this.httpApp.get(URL, {}, {}).then((response) => {//原生不需要处理url
let html = response.data;
html = html.replace(/data-src/g, "src")
.replace(/<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/g, '')
.replace(/style="visibility: hidden;"/,'style="visibility: visible;"')
// .replace(/https/g,'http');网上资料都说加这个方法,但是我加了之后图片不显示,去掉之后图片显示
let html_src = html;
resove(html_src);
}).catch((error) => {
reject(error);
})
})
}else{
return new Promise((resove, reject) => {
axios({
url: realurl,
method: 'get',
}).then((response) => {
let html = response.data;
html = html.replace(/data-src/g, "src")
.replace(/<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/g, '')
.replace(/style="visibility: hidden;"/,'style="visibility: visible;"')
// .replace(/https/g,'http');
let html_src = html;
resove(html_src);
}).catch((error) => {
reject(error);
});
})
}
}
2、使用innerHTML来显示内容
//ts
this.common.getWeixinContent(res.data.link).then((res:any)=>{
this.content = this.sanitizer.bypassSecurityTrustHtml(res);//获取返回Html
}).catch((err:any)=>{
})
//html
<div [innerHTML]="content" *ngIf="content" class="contentCSS"></div>//显示内容
3、<meta name="referrer" content="never">这句话也要加
----------------------------------------------------------------------------
新加 .replace(/style="visibility: hidden;"/,'style="visibility: visible;"')替换规则