簡體   English   中英

當我嘗試在反應應用程序中注冊服務工作者文件時,它會給我一個參考錯誤:未定義導航器

[英]When I try to register a service worker file in react app it will give me a reference error: navigator is not defined

export default function swDev() {
    let swUrl = `${process.env.PUBLIC_URL}/sw.js`
    if('serviceWorker' in navigator) {
        navigator.serviceWorker.register(swUrl).then((res) => {
            console.warn("response", res)
        }).catch((err) => {
            console.warn("error is: ", err)
        })
    } else {
        console.log("service worker is not supported")
    } 
}

這是以下代碼,我在我的 react 應用程序的 index.js 文件中也調用了這個 function。 還創建了一個簡單的 sw.js 文件,並附有該文件的消息。

您還應該檢查是否定義了 window。 服務工作者應該只在服務器端初始化

(typeof window != 'undefined' && window.document);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM