2 回答

TA貢獻1828條經驗 獲得超6個贊
該<base>
元素不會更改文檔的來源。您可以通過記錄來測試這一點self.origin
。
什么<base>
沒有做,但是,更改解析相對URL的基本URL。在這種情況下,您的 Service Worker 腳本是一個相對 URL。因此,而不是相對self.location
于其相對于新基地。
這意味著如果您提供<base>
跨域 URL,那么您的 Service Worker 腳本也將是跨域的。這將在您嘗試注冊時觸發錯誤。

TA貢獻1942條經驗 獲得超3個贊
我將發布我對錯誤的觀察,Failed to register a ServiceWorker: The document is in an invalid state.因為我找不到關于錯誤的太多信息。
當 iframe 被動態添加到文檔中時,從該 iframe 注冊 service worker 將導致上述錯誤。例如:
var iframe = document.createElement('iframe');
var html =
`<head>
<script src="./index.js" ></script>
</head>
<body>Foo</body>`;
document.body.appendChild(iframe);
iframe.contentWindow.document.open();
iframe.contentWindow.document.write(html);
iframe.contentWindow.document.close();
與在父 html 中靜態地擁有 iframe 不同,服務注冊將在其中工作。
<html>
<head></head>
<body>
<iframe>
<html>
<head>
<script src="./index.js"></script>
</head>
<body>
<h4>Foo</h4>
</body>
</html>
</iframe>
</body>
</html>
Service Worker 注冊代碼在 index.js 中,如下所示:
if ('serviceWorker' in navigator) {
navigator.serviceWorker.register('/sw.js')
.then((reg) => {
// registration worked
console.log('Registration succeeded. Scope is ' + reg.scope);
}).catch((error) => {
// registration failed
console.log('Registration failed with ' + error);
});
}
如果allow-same-origin啟用了沙箱,第二種情況甚至可以使用沙箱 iframe 。
添加回答
舉報