公司需求:公众号文章分享:
分享到微信正常,但是想要在iframe里面打开微信公众号文章,会报错,跨域问题,微信的限制;
然后网上大牛成熟的方法:core-anywhere,具体的原理就是把公众号文章里面的内容爬出来,然后前端将其渲染在页面中
https://github.com/Rob--W/cors-anywhere/。 仓库地址
代码:
本文是使用的jq,首先是通过ajaxProfilter对请求的url进行拼接,可以理解为请求拦截器,其实我感觉这个好像没什么必要,可能是因为是官方的demo,所以都是这样子写的,因为公众号的文章必须用https来搞,所以感觉这些判断都并没有什么用
$.ajaxPrefilter(function(options) {
if (options.crossDomain && jQuery.support.cors) {
if (options.url.indexOf('https://mp.weixin.qq.com/') != '-1') {
var http = (window.location.protocol === 'http:' ? 'http:' : 'https:');
// options.url = http + '//cors-anywhere.herokuapp.com/' + options.url;
//这个域名地址是在git上拉下来的node项目,跑在自己的服务器上,因为测试的那个太卡了
options.url = http + '//rob.gongziduan.com/' + options.url;
// options.url = 'http://localhost:8080/http://mp.weixin.qq.com/s/goJ9Ro-ZkQtzCN3T4bjQXQ/'
}
};
});
然后就是进入正文:
$.get(url, function(response) {
var html = response;
//因为是分享的需求,所以通过切割字符串,拿出文章的标题
let wodeccc = html.split('<meta property="twitter:title" content=')
wenzhangTitle = wodeccc[1].substring(0, wodeccc[1].indexOf("/>"))
//这个是将所有的http转换成https
html = html.replace(/data-src/g, "src").replace(/<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/g, '').replace(/https/g, 'http');
//注释的这个是处理在微信上打不开的问题,目前没有用到微信环境,而且
//这些转data的文本会出现在页面的头部,所以就直接去掉了
// var html_src = 'data:text/html;charset=utf-8,' + html;
// html_src = 'data:text/html;charset=utf-8,' + html;
html_src = html
//将内容赋值给页面的iframe
let iframe = document.getElementById('iFrame');
iframe.src = html_src;
var doc = iframe.contentDocument || iframe.document;
doc.write(html_src);
doc.getElementById("js_content").style.visibility = "visible";
});
需求完美解决,冲冲冲