天天看點

iframe嵌套微信公衆号文章

<iframe  style="min-height:100vh;width:100%;border-width: 0;"  id="iFrame" width="100%"></iframe>
           
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);





 // // 方法二
            // $.ajaxPrefilter( function (options) {
            //     if (options.crossDomain && jQuery.support.cors) {
            //         var http = (window.location.protocol === 'http:' ? 'http:' : 'https:');
            //         options.url = http + '//cors-anywhere.herokuapp.com/' + options.url;
            //     };
            // });

            // var share_link = "https://mp.weixin.qq.com/s/m6DZ4mPkPfpmLnUC9upO1A";    //這裡是微信文章位址

            // $.get( share_link, function (response){
            //     var html = response;
            //     html=html.replace(/data-src/g, "src");
            //     var html_src = 'data:text/html;charset=utf-8,' + html;
            //     $("#iFrame").attr("src" , html_src);
            // });
           

注意:這兩種方案都隻能将文字回顯出來,但是圖檔還是不能顯示。暫時還沒找到解決方案

js h5