微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

无法注册 Service Worker注册 ServiceWorker 失败:不支持当前源 ('null') 的 URL 协议

如何解决无法注册 Service Worker注册 ServiceWorker 失败:不支持当前源 ('null') 的 URL 协议

我正在为一个大学项目创建一个渐进式 Web 应用程序,但是当我检查控制台时出现以下错误: 无法注册 Service Worker。类型错误注册 ServiceWorker 失败

HTML 和 CSS 正按预期显示,但是当我从 Chrome Dev Tools 进行 PWA 审核时,它显示: canvas_image_editor_to_pwa .js:363 无法注册 Service Worker。 TypeError: Failed to register a ServiceWorker: 不支持当前源 ('null') 的 URL 协议。 在 window.onload 我是 javascript 和 html 的新手。我该怎么办?

我的所有文件都在同一个文件夹中,并且我使用的是 Windows 10。

更新:我在实时服务器上对其进行了测试,现在出现以下错误: 未捕获(承诺)类型错误:无法在“addAll”上执行“缓存”:serviceworker.js 文件中的请求失败

HTML:

<!DOCTYPE html>
<html>
    <head>
        <title>Image Editor</title>
        <Meta charset="UTF-8">
        <Meta name="viewport" content="width=device-width,initial-scale=1.0">
        <link rel="manifest" href="/manifest.json">
    </head>
    <body
        style="text-align: center;">
        <div>
            <input 
                id="filebrowser"
                type="file"
                accept="image/*">
        </div>

        <canvas 
            id="visibleCanvas"
            style="max-width: 100%;">
            Your browser...
        </canvas>

        <div>
            <button data-effect="normal">normal</button>
            <button data-effect="grayscale">Grayscale</button>
            <button data-effect="threshold">Threshold</button>
            <button data-effect="sephia">Sephia</button>
            <button data-effect="invert">Invert Colors</button>
            <button data-effect="pixelate">Pixelate</button>
            <button data-effect="2channels">2 Channels</button>
            <button data-effect="red">Red</button>
            <button data-effect="green">Green</button>
            <button data-effect="blue">Blue</button>
            <button data-effect="darker">Darker</button>
            <button data-effect="lighter">Lighter</button>
        </div>

        <div>
            <button id="btnDownload">Download</button>
            <!--<a id="btnDownload" href="#" download="imagine">Download</a>-->
        </div>
        <script src="C:\Users\andra\Desktop\Multimedia\Tema 3\canvas_image_editor_to_pwa .js"></script>
        <script src="C:\Users\andra\Desktop\Multimedia\Tema 3\serviceworker.js"></script>
        <script>
            "use strict";
            app.load();
        </script>

        <noscript>Your app can work without internet</noscript>
    </body>
</html>

Javascript:

"use strict";

const app = {
    offscreenCanvas:null,visibleCanvas:null,currentEffect:null
}

app.changeEffect = function(effect){
    if(effect !== app.currentEffect){
        app.currentEffect = effect;
        app.draw();
    }
}

app.draw = function(){
    //redimensionare canvas
    app.visibleCanvas.width=app.offscreenCanvas.width;
    app.visibleCanvas.height=app.offscreenCanvas.height;

    //desenare imagine pe visibleCanvas
    switch(app.currentEffect){
        case "normal":
            const vContext = visibleCanvas.getContext("2d");
            vContext.drawImage(app.offscreenCanvas,0);
            break;
        case "grayscale":
            app.grayscale();
            break;
        case "threshold":
            app.threshold(100);
            break;
        case "sephia":
            app.sephia();
            break;
        case "invert":
            app.invert();
            break;
        case "red":
            app.red();
            break;
        case "green":
            app.green();
            break;
        case "blue":
            app.blue();
            break;
        case "2channels":
            app.twochannels();
            break;
        case "darker":
            app.darker(100);
            break;
        case "lighter":
            app.lighter(100);
            break; 
        case "pixelate":
            app.pixelate2(10);
            break;   
    }
}

app.pixelate2 = function(dimBlock){
    const oContext = app.offscreenCanvas.getContext("2d");
    const vContext = app.visibleCanvas.getContext("2d");

    for(let x = 1; x < app.offscreenCanvas.width; x += dimBlock)
    {
        for(let y = 1; y < app.offscreenCanvas.height; y += dimBlock)
        {
            var pixel = oContext.getimageData(x,y,1,1);
            vContext.fillStyle = "rgb(" + pixel.data[0]+ "," +pixel.data[1]+ "," +pixel.data[2]+ ")";
            vContext.fillRect(x,x + dimBlock - 1,y + dimBlock - 1);
        }
    }
}

app.pixelate = function (step) {
    const oContext = app.offscreenCanvas.getContext("2d");
    const imageData = oContext.getimageData(0,app.offscreenCanvas.width,app.offscreenCanvas.height);
    const data = imageData.data;

    for (let i = 0; i<imageData.height;i+=step){

        const offsetLiniiAnterioare = i*(imageData.width*4);
        
        for(let j = 0; j<imageData.width; j+=step){

            let pij = j * 4 + offsetLiniiAnterioare;

            const r = data[pij]; //red 
            const g = data[pij + 1]; //green
            const b = data[pij + 2]; //blue

            for(let k = 0; k<step; k++)
                for (let l = 0; l<step; L++){
                    const kl = (i+k)*(imageData.width*4) + (j+l)*4;
                    data[kl] = r;
                    data[kl+1] = g;
                    data[kl+2] = b;
                }
        } 
    }

    const vContext = app.visibleCanvas.getContext("2d");
    vContext.putimageData(imageData,0);
}

app.lighter = function (val) {
    const oContext = app.offscreenCanvas.getContext("2d");
    const imageData = oContext.getimageData(0,app.offscreenCanvas.height);
    const data = imageData.data;

    for (let i = 0; i < data.length; i += 4) {
        data[i] += val //red
        data[i + 1] += val //green
        data[i + 2] += val //blue
    }
    const vContext = app.visibleCanvas.getContext("2d");
    vContext.putimageData(imageData,0);
}

app.darker = function (val) {
    const oContext = app.offscreenCanvas.getContext("2d");
    const imageData = oContext.getimageData(0,app.offscreenCanvas.height);
    const data = imageData.data;

    for (let i = 0; i < data.length; i += 4) {
        data[i] -= val //red
        data[i + 1] -= val //green
        data[i + 2] -= val //blue
    }
    const vContext = app.visibleCanvas.getContext("2d");
    vContext.putimageData(imageData,0);
}

app.twochannels = function () {
    const oContext = app.offscreenCanvas.getContext("2d");
    const imageData = oContext.getimageData(0,app.offscreenCanvas.height);
    const data = imageData.data;

    for (let i = 0; i < data.length; i += 4) {
        data[i + 2] = data[i + 1];
    }

    const vContext = app.visibleCanvas.getContext("2d");
    vContext.putimageData(imageData,0);
}

app.blue = function () {
    const oContext = app.offscreenCanvas.getContext("2d");
    const imageData = oContext.getimageData(0,app.offscreenCanvas.height);
    const data = imageData.data;

    for (let i = 0; i < data.length; i += 4) {
        data[i] = 0; //red
        data[i + 1] = 0; //green
        //data[i + 2] = 0; //blue
    }
    const vContext = app.visibleCanvas.getContext("2d");
    vContext.putimageData(imageData,0);
}

app.green = function () {
    const oContext = app.offscreenCanvas.getContext("2d");
    const imageData = oContext.getimageData(0,app.offscreenCanvas.height);
    const data = imageData.data;

    for (let i = 0; i < data.length; i += 4) {
        data[i] = 0; //red
        //data[i + 1] = 0; //green
        data[i + 2] = 0; //blue
    }
    const vContext = app.visibleCanvas.getContext("2d");
    vContext.putimageData(imageData,0);
}

app.red = function () {
    const oContext = app.offscreenCanvas.getContext("2d");
    const imageData = oContext.getimageData(0,app.offscreenCanvas.height);
    const data = imageData.data;

    for (let i = 0; i < data.length; i += 4) {
        //const r = data[i];
        //const g = data[i + 1];
        //const b = data[i + 2];
        
        //data[i] =  r;
        data[i + 1] = 0; //green
        data[i + 2] = 0; //blue
    }
    const vContext = app.visibleCanvas.getContext("2d");
    vContext.putimageData(imageData,0);
}

app.invert = function () {
    const oContext = app.offscreenCanvas.getContext("2d");
    const imageData = oContext.getimageData(0,app.offscreenCanvas.height);
    const data = imageData.data;

    for (let i = 0; i < data.length; i += 4) {
        const r = data[i];
        const g = data[i + 1];
        const b = data[i + 2];

        data[i] = 255 - data[i];
        data[i + 1] = 255 - data[i + 1];
        data[i + 2] = 255 - data[i + 2];
    }
    const vContext = app.visibleCanvas.getContext("2d");
    vContext.putimageData(imageData,0);
}

app.sephia=function(){
    const oContext=app.offscreenCanvas.getContext("2d");
    const imageData=oContext.getimageData(0,app.offscreenCanvas.height);
    const data=imageData.data;
    
    for(let i=0;i<data.length;i+=4){
        const R=data[i];
        const G=data[i+1];
        const B=data[i+2];

        //const average=Math.round((r+g+b)/3);
        const tr = 0.393*R + 0.769*G + 0.189*B
        const tg = 0.349*R + 0.686*G + 0.168*B
        const tb = 0.272*R + 0.534*G + 0.131*B

        //data[i] = 1000; -> 255

        /*if (tr > 255) 
            data[i] = 255 
        else */
        data[i] = tr;
        
        /*if (tg > 255) 
            data[i+1] = 255 
        else*/ data[i+1] = tg;

        /*if (tb > 255) 
            data[i+2] = 255 
        else*/ data[i+2] = tb;
    }
    const vContext=app.visibleCanvas.getContext("2d");
    vContext.putimageData(imageData,0);
}

app.threshold = function(threshold){
    const oContext=app.offscreenCanvas.getContext("2d");
    const imageData=oContext.getimageData(0,app.offscreenCanvas.height);
    const data=imageData.data;
    for(let i=0;i<data.length;i+=4){
        const r=data[i];
        const g=data[i+1];
        const b=data[i+2];
        const v = (0.2126*r + 0.7152*g + 0.0722*b >= threshold) ? 255 : 0;
         
        data[i]=data[i+1]=data[i+2]=v;
    }
    const vContext=app.visibleCanvas.getContext("2d");
    vContext.putimageData(imageData,0);
}

app.grayscale = function(){

    const oContext = app.offscreenCanvas.getContext("2d");
    const imageData = oContext.getimageData(0,app.offscreenCanvas.height);
    const data = imageData.data;
    for(let i=0; i<data.length; i+=4){
        let r = data[i]; //red
        let g = data[i+1]; //green
        let b = data[i+2]; //blue

        const average = Math.round((r + g + b) / 3);

        data[i] = data[i+1] = data[i+2] = average;
        //r = g = b = average;
    }

    const vContext = app.visibleCanvas.getContext("2d");
    vContext.putimageData(imageData,0);
}

app.load = function(){

    app.visibleCanvas = document.getElementById("visibleCanvas");
    app.offscreenCanvas = document.createElement("canvas"); //300*150


    /*document.getElementById("btnDownload").addEventListener("click",function(e)
    {
        const dataURL=app.visibleCanvas.toDataURL("image/png");
        console.log(dataURL);
        e.target.setAttribute("href",dataURL);
    });*/
    
    document.getElementById("btnDownload").addEventListener("click",()=>{
        const dataUrl=app.visibleCanvas.toDataURL();
        const link=document.createElement('a');
        link.download='image.png';
        link.href=dataUrl;
        link.click();
    });


    const buttons = document.querySelectorAll("button[data-effect]");
    for(let i=0; i<buttons.length; i++){
        buttons[i].addEventListener("click",function(ev){
            //ev.target
            //buttons[i]
            //this
            const effect = ev.target.dataset.effect;
            app.changeEffect(effect);
        })
    }

    document.getElementById("filebrowser").addEventListener("change",function(ev){
        const files = ev.target.files;

        const reader = new FileReader();
        reader.addEventListener("load",function(ev){
            const dataUrl = ev.target.result;

            const img = document.createElement("img");
            img.addEventListener("load",function(ev){              
                //redimensionare canvas
                app.offscreenCanvas.width=img.naturalWidth;
                app.offscreenCanvas.height=img.naturalHeight;

                //desenare imagine pe offscreenCanvas
                const oContext = app.offscreenCanvas.getContext("2d");
                oContext.drawImage(ev.target,0);             

                //desenare pe canvas vizibil
                app.currentEffect = "normal";
                app.draw();
            });
            img.src = dataUrl;
        });
        reader.readAsDataURL(files[0]);
    });
}

//Testeaza daca suporta serviceWorker
window.onload = () => {
    if('serviceWorker' in navigator){
        navigator.serviceWorker.register('C:\Users\andra\Desktop\Multimedia\Tema 3\serviceworker.js')
        .then((registration) => {
            console.log("Service worker registered");
            return registration;
        })
        .catch( (err) => {
            console.error("Unable to register the service worker. ",err);
        })
    }
}

Serviceworker:

const cacheName = "image-editor"
//const filesToCache = ['/Tema 3/canvas_image_editor_to_pwa.html','/Tema 3/canvas_image_editor_to_pwa.js']

//Porneste serviceworker si cache-ul aplicatiei
self.addEventListener('install',(e) => {
    e.waitUntil(
        caches.open(cacheName).then((cache) => {
            //return cache.addAll(filesToCache);
            return cache.addAll(['/Tema 3/','/Tema 3/canvas_image_editor_to_pwa.html','/Tema 3/canvas_image_editor_to_pwa.js']);
        })
    );
});

//Aplicatia se foloseste de aceste resurse cand e offline
self.addEventListener('fetch',(e) => {
    e.respondWith(caches.match(e.request).then((response) => {
        return response || fetch(e.request);
    }));
});

manifest.json:

{
    "name": "Canvas image editor","short_name": "Image editor","lang": "en-US","background_color": "white","theme_color": "white","display": "standalone","start_url": "/Tema 3/canvas_image_editor_to_pwa.html"
}

解决方法

尝试使用 Service Worker 的相对路径而不是完整路径(在您的情况下以 C:\ ... 开头)

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。