获取网站源代码的脚本(JavaScript)

huangapple go评论60阅读模式
英文:

script to get source code of website (js)

问题

我的学校封锁了CTRL + U,但你可以在链接之前使用'view-source:'来查看代码。这需要一些时间,所以我一直在尝试制作一个自动定向到源代码的脚本。但是,我一直遇到错误,因为它不是一个链接。

我已经尝试过以下方法:

var code = fetch(`view-source:https://${location.hostname}${location.pathname}`);
location.href = code;

var code = `view-source:https://${location.hostname}${location.pathname}`;
location.href = code;

在第一个方法中,我看到一个坏请求,而在第二个方法中,我看到一个带有"view-source:"后跟链接的空白页面。

英文:

My school blocked CTRL + U, but you can use 'view-source:' before a link to view the code. It takes awhile, so i've been trying to make a script to automatically direct to the source code. However, I keep getting errors because it is not a link

I have tried the following:

var code = fetch(`view-source:https://${location.hostname}${location.pathname}`);
location.href = (code);

and

var code = (`view-source:https://${location.hostname}${location.pathname}`);
location.href = (code);

In the first one, I see a bad request, and in the second, I a blank page with the words "view-source:" followed by the link

答案1

得分: 1

view-source: 不是一个你可以使用 fetch() 的真实协议。

然而,只需

var resp = await fetch('http://...');
var text = await resp.text();
document.body.textContent = text;

应该用该URL的文本内容替换当前文档的主体内容...

英文:

view-source: isn't a real protocol you can fetch().

However, just

var resp = await fetch('http://...');
var text = await resp.text();
document.body.textContent = text;

should replace the current document's body with the text contents of that URL...

答案2

得分: 1

如果您尝试从前端获取源代码,您将遇到CORS问题。但您可以像下面的示例中那样使用一些代理:

fetch('https://api.codetabs.com/v1/proxy?quest=https://stackoverflow.com/questions/75440023/script-to-get-source-code-of-website-js#75440023').then((response) => response.text()).then((text) => console.log(text));
英文:

If you try from frontend to fetch the source code you will run to CORS Problems. But you can use some proxyies like in the example beloow:

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

fetch(&#39;https://api.codetabs.com/v1/proxy?quest=https://stackoverflow.com/questions/75440023/script-to-get-source-code-of-website-js#75440023&#39;).then((response) =&gt; response.text()).then((text) =&gt; console.log(text));

<!-- end snippet -->

huangapple
  • 本文由 发表于 2023年2月14日 02:43:50
  • 转载请务必保留本文链接:https://go.coder-hub.com/75440023.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定