HtpsServiceWorker.html
<script>
if ('serviceWorker' in navigator) {
navigator.serviceWorker.register('./service-worker.js')
.then(function (registration) {
console.log('Service Worker 注册成功:', registration.scope);
})
.catch(function (error) {
console.log('Service Worker 注册失败:', error);
});
}
</script>
HtpstoHtpFetchAPI.html
<script>
// 检测URL是否以https开头,并转换为http
function convertURL(url) {
if (url.startsWith("https://")) {
return "http://" + url.substring(8);
}
return url;
}
const originalFetch = window.fetch;
window.fetch = function (url, options) {
// 在这里添加你的逻辑
console.log('About to fetch:', url);
// 调用原始的fetch方法
return originalFetch(convertURL(url), options).then(response => {
// 可以在这里对响应进行处理
return response;
}).catch(error => {
// 错误处理
console.error('Fetch error:', error);
throw error;
});
};
</script>
service-worker.js
//然后在service worker的脚本(service - worker.js)中,你可以监听fetch事件:
self.addEventListener('fetch', function (event) {
// 阻止默认的fetch行为
event.respondWith(
// 自定义处理逻辑
new Promise(function (resolve, reject) {
// 在这里添加你的逻辑
console.log('Request intercepted:', event.request.url);
// 修改请求的URL
var url = event.request.url;
if (event.request.url.startsWith("https://")) {
url = "http://" + url.substring(8);
}
const modifiedUrl = new URL(event.request.url);
modifiedUrl.pathname = url; // 修改为你想要的路径
// 可以使用fetch或其他方式获取响应
fetch(modifiedUrl).then(
function (response) {
// 可以在这里修改响应
resolve(response);
},
function (error) {
reject(error);
}
);
})
);
});