gpt4 book ai didi

javascript - 加载远程 Service Worker,在不同的域中运行?

转载 作者:行者123 更新时间:2023-11-29 15:31:11 24 4
gpt4 key购买 nike

我正在尝试在网站上放置一个 Service Worker,我想从 CDN 加载 Service Worker 脚本。但是,当我从不同的域加载服务 worker 时,出现以下错误。

ServiceWorker DOMException: Failed to register a ServiceWorker: The origin of the provided scriptURL ('https://cdndomain.com') does not match the current origin ('http://mydomain')

有没有办法从 CDN 加载 Service worker?我看到很少有推送通知服务在那里这样做,我们可以使用 eval 在本地执行服务 worker js 吗?

有什么解决方法吗?谢谢

这是我当前代码的样子

 if (navigator.serviceWorker) {
console.log("ServiceWorkerssupported");

navigator.serviceWorker.register('https://cdn.com/sw.js', {
scope: './'
})
.then(function(reg) {
console.log("ServiceWorkerstered", reg);
})
.catch(function(error) {
console.log("Failedegister ServiceWorker", error);
});
}

最佳答案

Service Worker 必须来自同一个域 - 因为 Service Worker 文件的位置很重要。

if ('serviceWorker' in navigator) {
navigator.serviceWorker.register('/sw.js').then(function(registration) {
// Registration was successful
console.log('ServiceWorker registration successful with scope: ', registration.scope);
}).catch(function(err) {
// registration failed :(
console.log('ServiceWorker registration failed: ', err);
});
}

One subtlety with the register method is the location of the service worker file. You'll notice in this case that the service worker file is at the root of the domain. This means that the service worker's scope will be the entire origin. In other words, this service worker will receive fetch events for everything on this domain. If we register the service worker file at /example/sw.js, then the service worker would only see fetch events for pages whose URL starts with /example/ (i.e. /example/page1/, /example/page2/).

您可以使用 php 脚本作为代理从其他地方加载它。

关于javascript - 加载远程 Service Worker,在不同的域中运行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34671169/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com