如何使用JavaScript查看所有网站的源代码?

yfjy0ee7  于 2022-11-27  发布在  Java
关注(0)|答案(1)|浏览(133)

我想用JavaScript来获取用户的URL并返回网站的源代码。我想用它来创建一个iframe,但要用实际的代码。
例如:

let userUrl = prompt("What website do you want displayed?","e.g. https://www.google.com");

function getSource(url){

//some code
return pageSource;
}
document.body.innerHtml=getSource(userUrl);

我试着抓取一个view page source网站,并将其转换为一个API,我可以将其注入JavaScript,但我没有运气。

4uqofj5v

4uqofj5v1#

<html>
<head><meta charset="us-ascii">
    <title></title>
<script>

let userUrl = prompt("What website do you want displayed?","e.g. 
https://www.google.com");

if (userUrl){

    var srcFrame=""; //complete page code to inject into your iframe or return

    var fetchMe = "https://api.codetabs.com/v1/proxy?quest=" + userUrl;

    fetch(fetchMe).then((response) => response.text()).then((text) => {
        srcFrame = text;

        //if injecting into iframe
        myFrame.document.open();
        myFrame.document.write(srcFrame);
        myFrame.document.close();


        // USE THE FOLLOWING TO ADD THE ORIGINAL URL AS THE baseURI SO RELATIVE 
        //LINKS & SCRIPTS WILL WORK AND ACCESS THE ORIGINAL SOURCE AND NOT YOUR 
        //SERVER
        var addOrigBase= document.createElement('base');
        addOrigBase.setAttribute('href',userUrl);
    
   document.getElementById("myFrame").contentDocument.head.appendChild(addOrigBase);

    });

};

</script>
</head>
<body>
<iframe onload="myFrame.frameElement.height = 
(myFrame.frameElement.contentDocument.body.clientHeight)+10" frameborder="" 
height="25px" id="myFrame" name="myFrame" scrolling="no" src="about:blank"  
width="100%"></iframe>
</body>
</html>

相关问题