Skip to content
This repository has been archived by the owner on Feb 3, 2022. It is now read-only.

Uncaught (in promise) TypeError: Failed to execute 'fetch' on 'ServiceWorkerGlobalScope': 'only-if-cached' can be set only with 'same-origin' mode SOLVED #20

Closed
MMB1983 opened this issue Feb 20, 2018 · 9 comments

Comments

@MMB1983
Copy link

MMB1983 commented Feb 20, 2018

I am running Magento CE 1.9.3.7 and I have this error in Chrome v.64
Uncaught (in promise) TypeError: Failed to execute 'fetch' on 'ServiceWorkerGlobalScope': 'only-if-cached' can be set only with 'same-origin' mode in serviceworker.js:67
Any idea how to solve this ?
What I also did:
I fixed problem mentioned in issue #18
I also removed comments from serviceworker.js line 7-14 due to error :
Uncaught SyntaxError: Unexpected token *

@tgerulaitis
Copy link
Member

@MMB1983, Could you please post your app/design/frontend/base/default/template/pwa/serviceworker/serviceworker.js file?

@MMB1983
Copy link
Author

MMB1983 commented Feb 20, 2018

'use strict';

const version = '<?php echo $this->getVersion() ?>';
const offlinePage = '<?php echo $this->getOfflinePageUrl() ?>';
const urlBlacklist = <?php echo json_encode($this->getOfflineUrlBlacklist()) ?>;

function updateStaticCache() {
    return caches.open(version)
        .then(cache => {
            return cache.addAll([
                offlinePage
            ]);
        });
}

function clearOldCaches() {
    return caches.keys().then(keys => {
        return Promise.all(
            keys
                .filter(key => key.indexOf(version) !== 0)
                .map(key => caches.delete(key))
        );
    });
}

function isHtmlRequest(request) {
    return request.headers.get('Accept').indexOf('text/html') !== -1;
}


function isBlacklisted(url) {
    return urlBlacklist.filter(bl => url.indexOf(bl) == 0).length > 0;
}


function isCachableResponse(response) {
    return response && response.ok;
}


self.addEventListener('install', event => {
    event.waitUntil(
        updateStaticCache()
            .then(() => self.skipWaiting())
    );
});


self.addEventListener('activate', event => {
    event.waitUntil(
        clearOldCaches()
            .then(() => self.clients.claim())
    );
});


self.addEventListener('fetch', event => {
    let request = event.request;

    if (request.method !== 'GET') {
        
        if (!navigator.onLine && isHtmlRequest(request)) {
            return event.respondWith(caches.match(offlinePage));
        }
        return;
    }

    if (isHtmlRequest(request)) {
        
        event.respondWith(
            fetch(request)
                .then(response => {
                    if (isCachableResponse(response) && !isBlacklisted(response.url)) {
                        let copy = response.clone();
                        caches.open(version).then(cache => cache.put(request, copy));
                    }
                    return response;
                })
                .catch(() => {
                    return caches.match(request)
                        .then(response => {
                            if (!response && request.mode == 'navigate') {
                                return caches.match(offlinePage);
                            }
                            return response;
                        });
                })
        );
    } else {
        
        event.respondWith(
            caches.match(request)
                .then(response => {
                    return response || fetch(request)
                            .then(response => {
                                if (isCachableResponse(response)) {
                                    let copy = response.clone();
                                    caches.open(version).then(cache => cache.put(request, copy));
                                }
                                return response;
                            })
                })
        );
    }
});

But this issue can be closed now as the error disappeared. This might be something related with AMP pages as I do have them as well so now I will try to combine AMP and PWA.

@MMB1983
Copy link
Author

MMB1983 commented Apr 3, 2018

I keep having the same error so I added this
if (event.request.cache === 'only-if-cached' && event.request.mode !== 'same-origin')
return
And all errors are gone :-)
Ps. Correct me if I am wrong

My polished serviceworkers.js looks like this:

'use strict';

const version = '<?php echo $this->getVersion() ?>';
const offlinePage = '<?php echo $this->getOfflinePageUrl() ?>';
const urlBlacklist = <?php echo json_encode($this->getOfflineUrlBlacklist()) ?>;

function updateStaticCache() {
    return caches.open(version)
        .then(cache => {
            return cache.addAll([
                offlinePage
            ]);
        });
}

function clearOldCaches() {
    return caches.keys().then(keys => {
        return Promise.all(
            keys
                .filter(key => key.indexOf(version) !== 0)
                .map(key => caches.delete(key))
        );
    });
}

function isHtmlRequest(request) {
    return request.headers.get('Accept').indexOf('text/html') !== -1;
}


function isBlacklisted(url) {
    return urlBlacklist.filter(bl => url.indexOf(bl) == 0).length > 0;
}


function isCachableResponse(response) {
    return response && response.ok;
}


self.addEventListener('install', event => {
    event.waitUntil(
        updateStaticCache()
            .then(() => self.skipWaiting())
    );
});


self.addEventListener('activate', event => {
    event.waitUntil(
        clearOldCaches()
            .then(() => self.clients.claim())
    );
});


self.addEventListener('fetch', event => {
    let request = event.request;

    if (request.method !== 'GET') {
        
        if (!navigator.onLine && isHtmlRequest(request)) {
            return event.respondWith(caches.match(offlinePage));
        }
        return;
    }

    if (isHtmlRequest(request)) {
        
        event.respondWith(
            fetch(request)
                .then(response => {
                    if (isCachableResponse(response) && !isBlacklisted(response.url)) {
                        let copy = response.clone();
                        caches.open(version).then(cache => cache.put(request, copy));
                    }
                    return response;
                })
                .catch(() => {
                    return caches.match(request)
                        .then(response => {
                            if (!response && request.mode == 'navigate') {
                                return caches.match(offlinePage);
                            }
                            return response;
                        });
                })
        );
    } else {
if (event.request.cache === 'only-if-cached' && event.request.mode !== 'same-origin')
      return
        event.respondWith(
            caches.match(request)
                .then(response => {
                    return response || fetch(request)
                            .then(response => {
                                if (isCachableResponse(response)) {
                                    let copy = response.clone();
                                    caches.open(version).then(cache => cache.put(request, copy));
                                }
                                return response;
                            })
                })
        );
    }
});

@MMB1983 MMB1983 changed the title Uncaught (in promise) TypeError: Failed to execute 'fetch' on 'ServiceWorkerGlobalScope': 'only-if-cached' can be set only with 'same-origin' mode Uncaught (in promise) TypeError: Failed to execute 'fetch' on 'ServiceWorkerGlobalScope': 'only-if-cached' can be set only with 'same-origin' mode SOLVED Apr 3, 2018
@tgerulaitis
Copy link
Member

Not sure why the service worker was complaining about only-if-cached flag, but I'm glad you found a fix!

@leonardosedevic
Copy link

leonardosedevic commented Jun 10, 2018

hi everyone i have this error:

The FetchEvent for "https://www.stop-it.be/" resulted in a network error response: the promise was rejected.
service-worker.js:69 Uncaught (in promise) TypeError: Failed to execute 'fetch' on 'ServiceWorkerGlobalScope': 'only-if-cached' can be set only with 'same-origin' mode
at service-worker.js:69

this is my code:

// Here we add an event listener for the "install" event. 
// Once it registers successfully, it will automatically 
// install the service worker for you. Cool!

this.addEventListener('install', function(event) {
    console.log('installing....');

    // Here we are once again using promises! the event 
    // object has a waitUntil property that is a promise. 
    // This promise waits until the cache portions (below) // are populated before declaring the service worker 
    // "installed!"

    event.waitUntil(

        // See this 'v1' here? That's the version of your 
        // Service Worker cache. If you ever need to add 
        // new dependencies in the future, you'll have to 
        // use the "delete" functionality below and make 
        // this a 'v2' //(or whatever you wish to call it.

        caches.open('v1').then(function(cache) {
            return cache.addAll([
                //  These are the files we want to cache so // we can access offline! For your project 
                // you'll need to add your own. You can 
                // include any file you wish here.
                'index.html',
                'js/app.js',
                'css/style.css'

            ]);
        })
    );
});


// This is where the really cool stuff happens. We make use 
// of the Fetch API in order to first check the cached 
// resources, then if those don't exist, we check the 
// server, if we are online. Essentially, this is great for 
// both offline mode as well as from a site speed 
// standpoint!

this.addEventListener('fetch', function(event) {
    // Full documentation for respondWith is available on 
    // MDN (http://mzl.la/1SKtV92), but basically with this
    // you are able to customize the response from the 
    // request you initially get by the browser.

    event.respondWith(

    // caches.open look familiar? It should! We just used 
    // it in the code above! Here we are finding a match 
    // for the event.request in our cached v1 storage (in 
    // the browser). 
    //
    // If we find a match for the request in the cache 
    // storage, that means our service worker will serve 
    // that file right up from the browser itself rather 
    // than going alllll the way to the server to get it! 
    // NICE!!!

    // However, if the resource isn't found, then it WILL 
    // go ALLLL the way to the server to grab it, or if 
    // it's in offline mode, will break and not show the 
    // file. Bummer!

        caches.open('v1').then(function(cache) {
            return cache.match(event.request).then(function(response) {
                return response || fetch(event.request).then(function(response) {
                    cache.put(event.request, response.clone());
                    return response;
                });
            });
        })
    );
});

// An event listener for the 'activate' functionality that
// goes along with Service Worker registration. 

this.addEventListener('activate', function activator(event) {
    console.log('activate!');

    // Here we see another wait until....
    event.waitUntil(

        // I won't go too much into detail here because 
        // there's a lot of stuff you can look up yourself // (filter() and map() being two of them), but 
        // basically this function is in case there's 
        // previously cached content, then we get rid of 
        // it and populate it with the newest cached 
        // content. This is only if you need them to 
        // install a v2, v3, v4, etc... In a nutshell it 
        // wipes out their previous cache and replaces it 
        // with the new version. 
        
        caches.keys().then(function(keys) {
            return Promise.all(keys
                .filter(function(key) {
                    return key.indexOf('v1') !== 0;
                })
                .map(function(key) {
                    return caches.delete(key);
                })
            );
        })
    );
});

@tgerulaitis
Copy link
Member

@leonardosedevic ,

What browser are you using?

Looks like there's an open bug in Chrome, where the service worker fetches can fail if developer tools are open: https://bugs.chromium.org/p/chromium/issues/detail?id=823392

@leonardosedevic
Copy link

i use the latest version of chrome. i get that error when i use lighthouse for cleaning my code, making everything nice and clean

@gtamborero
Copy link

This error appears on my Computer 'Chrome Web Console' but the "add to home button" works perfectly over a phone with Chrome

@BLecha
Copy link

BLecha commented May 31, 2019

I keep having the same error so I added this
if (event.request.cache === 'only-if-cached' && event.request.mode !== 'same-origin')
return
And all errors are gone :-)
Ps. Correct me if I am wrong

My polished serviceworkers.js looks like this:

'use strict';

const version = '<?php echo $this->getVersion() ?>';
const offlinePage = '<?php echo $this->getOfflinePageUrl() ?>';
const urlBlacklist = <?php echo json_encode($this->getOfflineUrlBlacklist()) ?>;

function updateStaticCache() {
    return caches.open(version)
        .then(cache => {
            return cache.addAll([
                offlinePage
            ]);
        });
}

function clearOldCaches() {
    return caches.keys().then(keys => {
        return Promise.all(
            keys
                .filter(key => key.indexOf(version) !== 0)
                .map(key => caches.delete(key))
        );
    });
}

function isHtmlRequest(request) {
    return request.headers.get('Accept').indexOf('text/html') !== -1;
}


function isBlacklisted(url) {
    return urlBlacklist.filter(bl => url.indexOf(bl) == 0).length > 0;
}


function isCachableResponse(response) {
    return response && response.ok;
}


self.addEventListener('install', event => {
    event.waitUntil(
        updateStaticCache()
            .then(() => self.skipWaiting())
    );
});


self.addEventListener('activate', event => {
    event.waitUntil(
        clearOldCaches()
            .then(() => self.clients.claim())
    );
});


self.addEventListener('fetch', event => {
    let request = event.request;

    if (request.method !== 'GET') {
        
        if (!navigator.onLine && isHtmlRequest(request)) {
            return event.respondWith(caches.match(offlinePage));
        }
        return;
    }

    if (isHtmlRequest(request)) {
        
        event.respondWith(
            fetch(request)
                .then(response => {
                    if (isCachableResponse(response) && !isBlacklisted(response.url)) {
                        let copy = response.clone();
                        caches.open(version).then(cache => cache.put(request, copy));
                    }
                    return response;
                })
                .catch(() => {
                    return caches.match(request)
                        .then(response => {
                            if (!response && request.mode == 'navigate') {
                                return caches.match(offlinePage);
                            }
                            return response;
                        });
                })
        );
    } else {
if (event.request.cache === 'only-if-cached' && event.request.mode !== 'same-origin')
      return
        event.respondWith(
            caches.match(request)
                .then(response => {
                    return response || fetch(request)
                            .then(response => {
                                if (isCachableResponse(response)) {
                                    let copy = response.clone();
                                    caches.open(version).then(cache => cache.put(request, copy));
                                }
                                return response;
                            })
                })
        );
    }
});

Did for me as well the job! Thanks a lot!

englishextra added a commit to englishextra/englishextra.github.io that referenced this issue Sep 29, 2020
if (event.request.cache === 'only-if-cached' && event.request.mode !== 'same-origin')
return
And all errors are gone :-) meanbee/magento-meanbee-pwa#20 (comment)
englishextra added a commit to lovespy/lovespy.github.io that referenced this issue Sep 29, 2020
if (event.request.cache === 'only-if-cached' && event.request.mode !== 'same-origin')
return
And all errors are gone :-) meanbee/magento-meanbee-pwa#20 (comment)
englishextra added a commit to englishextra/lovespy-muicss-dev that referenced this issue Sep 29, 2020
if (event.request.cache === 'only-if-cached' && event.request.mode !== 'same-origin')
return
And all errors are gone :-) meanbee/magento-meanbee-pwa#20 (comment)
englishextra added a commit to mytushino/mytushino.github.io that referenced this issue Sep 29, 2020
if (event.request.cache === 'only-if-cached' && event.request.mode !== 'same-origin')
return
And all errors are gone :-) meanbee/magento-meanbee-pwa#20 (comment)
englishextra added a commit to englishextra/mytushino-muicss-dev that referenced this issue Sep 29, 2020
if (event.request.cache === 'only-if-cached' && event.request.mode !== 'same-origin')
return
And all errors are gone :-) meanbee/magento-meanbee-pwa#20 (comment)
englishextra added a commit to noushevr/noushevr.github.io that referenced this issue Sep 29, 2020
if (event.request.cache === 'only-if-cached' && event.request.mode !== 'same-origin')
return
And all errors are gone :-) meanbee/magento-meanbee-pwa#20 (comment)
englishextra added a commit to englishextra/serguei-muicss-dev that referenced this issue Sep 29, 2020
if (event.request.cache === 'only-if-cached' && event.request.mode !== 'same-origin')
return
And all errors are gone :-) meanbee/magento-meanbee-pwa#20 (comment)
englishextra added a commit to englishextra/serguei-uwp-dev that referenced this issue Sep 29, 2020
if (event.request.cache === 'only-if-cached' && event.request.mode !== 'same-origin')
return
And all errors are gone :-) meanbee/magento-meanbee-pwa#20 (comment)
englishextra added a commit to yuzhtushino/yuzhtushino.github.io that referenced this issue Sep 29, 2020
if (event.request.cache === 'only-if-cached' && event.request.mode !== 'same-origin')
return
And all errors are gone :-) meanbee/magento-meanbee-pwa#20 (comment)
englishextra added a commit to englishextra/shimansky.biz that referenced this issue Sep 29, 2020
if (event.request.cache === 'only-if-cached' && event.request.mode !== 'same-origin')
return
And all errors are gone :-) meanbee/magento-meanbee-pwa#20 (comment)
englishextra added a commit to englishextra/englishextra.github.io that referenced this issue Sep 30, 2020
englishextra added a commit to englishextra/lovespy-muicss-dev that referenced this issue Sep 30, 2020
englishextra added a commit to mytushino/mytushino.github.io that referenced this issue Sep 30, 2020
englishextra added a commit to englishextra/mytushino-muicss-dev that referenced this issue Sep 30, 2020
englishextra added a commit to englishextra/serguei-muicss-dev that referenced this issue Sep 30, 2020
englishextra added a commit to englishextra/serguei-uwp-dev that referenced this issue Sep 30, 2020
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

No branches or pull requests

5 participants