如果我有一个网站处理信息或发送链接为
https://example.com
,我将如何将所有网络请求更改为https://example.org
?这包括网站获取的任何信息。
我尝试使用
href
查找属性 src
和 getAttribute
但仍然错过了一些请求。我该如何找到一种方法来做到这一点?
我当前的代码是这样的:
<!DOCTYPE html>
<html>
<head>
<title>NoGuardian</title>
<style>
body {
margin: 0;
}
iframe#page {
border: 0;
width: 100%;
height: 100vh;
position: fixed;
}
</style>
</head>
<body>
<iframe id="page"></iframe>
<script>
`use strict`;
if (window.location.search.charAt(window.location.search.length - 1) === `/`) {
window.location.search = window.location.search.slice(0, window.location.search.length - 1);
}
if (window.location.search.slice(1, 9) == `https://`) {
window.location.search = window.location.search.slice(9);
}
else if (window.location.search.slice(1, 8) == `http://`) {
window.location.search = window.location.search.slice(8);
}
fetch(`https://api.codetabs.com/v1/proxy?quest=${window.location.search.slice(1)}`).then((response) => response.text()).then((text) => {
const iframe = document.getElementById(`page`);
iframe.setAttribute(`srcdoc`, text);
iframe.addEventListener(`load`, function() {
for (let elements = 0; elements < iframe.contentWindow.document.getElementsByTagName(`*`).length; elements++) {
if (iframe.contentWindow.document.getElementsByTagName(`*`)[elements].getAttribute(`src`) != null) {
if (iframe.contentWindow.document.getElementsByTagName(`*`)[elements].getAttribute(`src`).slice(0, 1) == `/`) {
iframe.contentWindow.document.getElementsByTagName(`*`)[elements].setAttribute(`src`, `${window.location.search.slice(1)}${iframe.contentWindow.document.getElementsByTagName(`*`)[elements].getAttribute(`src`)}`);
}
else if (iframe.contentWindow.document.getElementsByTagName(`*`)[elements].getAttribute(`src`).slice(0, 2) == `./`) {
iframe.contentWindow.document.getElementsByTagName(`*`)[elements].setAttribute(`src`, `${window.location.search.slice(1)}${iframe.contentWindow.document.getElementsByTagName(`*`)[elements].getAttribute(`src`).slice(1, iframe.contentWindow.document.getElementsByTagName(`*`)[elements].getAttribute(`src`).length - 1)}`);
}
// console.log(`href: ${iframe.contentWindow.document.getElementsByTagName(`*`)[elements].getAttribute(`src`)}`)
}
if (iframe.contentWindow.document.getElementsByTagName(`*`)[elements].getAttribute(`href`) != null) {
// console.log(`src: ${iframe.contentWindow.document.getElementsByTagName(`*`)[elements].getAttribute(`href`)}`)
}
}
});
});
</script>
</body>
</html>
我还用代码检测
href
,但删除了该部分以将其最小化。
您的方法仅替换 HTML 上的
src
和 href
并且仅在初始加载时替换。您还需要处理动态创建的元素(例如动态创建的图像、脚本、样式表等)、srcset
、CSS 中加载的资源(例如字体、背景图像)、XHR/fetch、JavaScript 等情况通过 import
加载的模块等等。
考虑研究Service Workers。这允许您编写位于 Web 应用程序和网络之间的代码,从而允许您拦截请求并提供自定义响应。