亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

iFrame 中的 Service Worker

iFrame 中的 Service Worker

慕工程0101907 2021-08-20 18:07:59
我正在嘗試在 iframe 中初始化一個 service worker。我知道 Service Worker 在起源方面有安全限制,但據我所知,設置base應該可以解決這個問題。<html>   <base href="http://127.0.0.1:9090">   <script>     if ('serviceWorker' in navigator) {        window.addEventListener('load', function() {          navigator.serviceWorker.register('/sw.js').then(function(reg) {            if(reg.installing) {              console.log('Service worker installing');            } else if(reg.waiting) {              console.log('Service worker installed');            } else if(reg.active) {              console.log('Service worker active');              console.log(self)            }          }).catch(function(error) {            // registration failed            console.log('Registration failed with ' + error);          });        });      }   </script>錯誤: Registration failed with InvalidStateError: Failed to register a ServiceWorker: The document is in an invalid state.如果我修改 base,它會抱怨起源不一樣,所以 service worker 與 base href 有一定的聯系。我在這里缺少什么?
查看完整描述

2 回答

?
30秒到達戰場

TA貢獻1828條經驗 獲得超6個贊

<base>元素不會更改文檔的來源。您可以通過記錄來測試這一點self.origin。

什么<base>沒有做,但是,更改解析相對URL的基本URL。在這種情況下,您的 Service Worker 腳本是一個相對 URL。因此,而不是相對self.location于其相對于新基地。

這意味著如果您提供<base>跨域 URL,那么您的 Service Worker 腳本也將是跨域的。這將在您嘗試注冊時觸發錯誤。


查看完整回答
反對 回復 2021-08-20
?
手掌心

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 。


查看完整回答
反對 回復 2021-08-20
  • 2 回答
  • 0 關注
  • 656 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號