iframe嵌套微信公众号文章

3,049 阅读1分钟

首先写一个irfame标签,src不需要写,后面会动态添加

<iframe  style="min-height:100vh;width:100%;border-width: 0;"  id="iFrame" width="100%"></iframe>

话不多说直接上js代码


function getUrl(URL) {  
let http = (window.location.protocol === 'http:' ? 'http:' : 'https:');  

//调用跨域API  

let realurl = http + '//cors-anywhere.herokuapp.com/' + URL;  

$.ajax({  

type: 'get',  

url: realurl,  

success: function (response) {  

if (response) {  

let html = response;  

html = html.replace(/data-src/g, "src")  

.replace(/<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/g, '')  

.replace(/https/g, 'http');  

// let html_src = 'data:text/html;charset=utf-8,' + html;  

let html_src = html;  

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";  

}  

},  

error: function (err) {  

console.log(err);  

alert('好像出错了...');  

}  

});  
}  

//调用getUrl方法,url为微信公众号文章链接  
var url = "https://mp.weixin.qq.com/s/m6DZ4mPkPfpmLnUC9upO1A";  
getUrl(url);