Skip to Content
Odoo Menu
  • Log ind
  • Prøv gratis
  • Apps
    Økonomi
    • Bogføring
    • Fakturering
    • Udgifter
    • Regneark (BI)
    • Dokumenter
    • e-Signatur
    Salg
    • CRM
    • Salg
    • POS Butik
    • POS Restaurant
    • Abonnementer
    • Udlejning
    Hjemmeside
    • Hjemmesidebygger
    • e-Handel
    • Blog
    • Forum
    • LiveChat
    • e-Læring
    Forsyningskæde
    • Lagerbeholdning
    • Produktion
    • PLM
    • Indkøb
    • Vedligeholdelse
    • Kvalitet
    HR
    • Medarbejdere
    • Rekruttering
    • Fravær
    • Medarbejdersamtaler
    • Anbefalinger
    • Flåde
    Marketing
    • Markedsføring på sociale medier
    • E-mailmarketing
    • SMS-marketing
    • Arrangementer
    • Automatiseret marketing
    • Spørgeundersøgelser
    Tjenester
    • Projekt
    • Timesedler
    • Udkørende Service
    • Kundeservice
    • Planlægning
    • Aftaler
    Produktivitet
    • Dialog
    • Godkendelser
    • IoT
    • VoIP
    • Vidensdeling
    • WhatsApp
    Tredjepartsapps Odoo Studio Odoo Cloud-platform
  • Brancher
    Detailhandel
    • Boghandel
    • Tøjforretning
    • Møbelforretning
    • Dagligvarebutik
    • Byggemarked
    • Legetøjsforretning
    Mad og værtsskab
    • Bar og pub
    • Restaurant
    • Fastfood
    • Gæstehus
    • Drikkevareforhandler
    • Hotel
    Ejendom
    • Ejendomsmægler
    • Arkitektfirma
    • Byggeri
    • Ejendomsadministration
    • Havearbejde
    • Boligejerforening
    Rådgivning
    • Regnskabsfirma
    • Odoo-partner
    • Marketingbureau
    • Advokatfirma
    • Rekruttering
    • Audit & certificering
    Produktion
    • Tekstil
    • Metal
    • Møbler
    • Fødevareproduktion
    • Bryggeri
    • Firmagave
    Heldbred & Fitness
    • Sportsklub
    • Optiker
    • Fitnesscenter
    • Kosmetolog
    • Apotek
    • Frisør
    Håndværk
    • Handyman
    • IT-hardware og support
    • Solenergisystemer
    • Skomager
    • Rengøringsservicer
    • VVS- og ventilationsservice
    Andet
    • Nonprofitorganisation
    • Miljøagentur
    • Udlejning af billboards
    • Fotografi
    • Cykeludlejning
    • Softwareforhandler
    Gennemse alle brancher
  • Community
    Få mere at vide
    • Tutorials
    • Dokumentation
    • Certificeringer
    • Oplæring
    • Blog
    • Podcast
    Bliv klogere
    • Udannelselsesprogram
    • Scale Up!-virksomhedsspillet
    • Besøg Odoo
    Få softwaren
    • Download
    • Sammenlign versioner
    • Udgaver
    Samarbejde
    • Github
    • Forum
    • Arrangementer
    • Oversættelser
    • Bliv partner
    • Tjenester til partnere
    • Registrér dit regnskabsfirma
    Modtag tjenester
    • Find en partner
    • Find en bogholder
    • Kontakt en rådgiver
    • Implementeringstjenester
    • Kundereferencer
    • Support
    • Opgraderinger
    Github Youtube Twitter LinkedIn Instagram Facebook Spotify
    +1 (650) 691-3277
    Få en demo
  • Prissætning
  • Hjælp

Odoo is the world's easiest all-in-one management software.
It includes hundreds of business apps:

  • CRM
  • e-Commerce
  • Bogføring
  • Lager
  • PoS
  • Projekt
  • MRP
All apps
Du skal være registreret for at interagere med fællesskabet.
All Posts People Emblemer
Tags (View all)
odoo accounting v14 pos v15
Om dette forum
Du skal være registreret for at interagere med fællesskabet.
All Posts People Emblemer
Tags (View all)
odoo accounting v14 pos v15
Om dette forum
Hjælp

Service worker `fetch` fails in `install` event when trying to cache assets

Tilmeld

Få besked, når der er aktivitet på dette indlæg

Dette spørgsmål er blevet anmeldt
webclientjavascriptdevelopmentsaleschrome
2 Besvarelser
965 Visninger
Avatar
Nyan Min Htet

Hello everyone,


  I am trying to implement offline functionality for the Odoo Sales app using a custom service worker. I am facing an issue where the

  service worker fails to fetch the list of assets to cache during its install event.


  Here's what I have done so far:


  1.    Created a custom Odoo module (pwa_sales_offline) that depends on web, sale_management, and stock.
  2.    Created a custom service worker at pwa_sales_offline/static/src/service_worker.js.
  3. Overridden the default service worker by creating a controller that inherits from odoo.addons.web.controllers.webmanifest.WebManifest and overrides the _get_service_worker_content method to serve my custom file.
  4. Created a controller to get the list of assets. This controller calls request.env['ir.qweb']._get_asset_nodes('web.assets_backend', True, True, False, False, request.env.context) and returns the list of asset URLs as a JSON response.
  5. The service worker's install event fetches this list of assets and tries to cache them using cache.addAll().


  The Problem:


  ​The fetch call within the service worker's install event fails with the error: Uncaught (in promise) TypeError: Failed to fetch.


  What I have tried:


   * I have verified that the controller that returns the list of assets is working correctly by opening its URL (/pwa_sales_offline/assets)

     directly in the browser. It successfully returns a JSON array of asset URLs.

   * I have tried changing the auth of the controller to public.

   * I have tried changing the type of the controller to both http and json.

   * I have added a check in the service worker's fetch event to prevent it from intercepting its own requests to the assets endpoint.


  The Code:


  Here is the relevant code:


import logging

import json

from odoo import http

from odoo.http import request

from odoo.tools import file_open

from odoo.addons.web.controllers.webmanifest import WebManifest


_logger = logging.getLogger(__name__)


class PwaSalesOfflineWebManifest(WebManifest):

def _get_service_worker_content(self):

_logger.info("Serving custom service worker")

with file_open('pwa_sales_offline/static/src/service_worker.js') as f:

return f.read()


@http.route('/pwa_sales_offline/assets', type='http', auth='public', methods=['GET'], csrf=False)

def get_assets(self):

_logger.info("Getting assets for PWA")

qweb = request.env['ir.qweb']

nodes = qweb._get_asset_nodes('web.assets_backend', True, True, False, False, request.env.context)

files = []

for node in nodes:

if len(node) == 2:

tag, attrs = node

if 'href' in attrs:

files.append(attrs['href'])

elif 'src' in attrs:

files.append(attrs['src'])

elif len(node) == 3:

tag, attrs, content = node

if 'href' in attrs:

files.append(attrs['href'])

elif 'src' in attrs:

files.append(attrs['src'])

_logger.info("Found %d assets", len(files))

return request.make_json_response(files)

const STATIC_CACHE_NAME = 'odoo-sales-offline-static-cache';


self.addEventListener('install', (event) => {

console.log('Custom Service Worker: Installed!');

event.waitUntil(

fetch('/pwa_sales_offline/assets').then((response) => {

return response.json();

}).then((files) => {

return caches.open(STATIC_CACHE_NAME).then((cache) => {

return cache.addAll(files);

});

})

);

});


self.addEventListener('fetch', (event) => {

console.log('Custom Service Worker: Fetching', event.request.url);

const url = new URL(event.request.url);


if (url.pathname === '/pwa_sales_offline/assets') {

return;

}


// Serve static assets from cache

if (url.origin === location.origin) {

event.respondWith(

caches.match(event.request).then((response) => {

return response || fetch(event.request);

})

);

return;

}


// Cache data

const DATA_CACHE_NAME = 'odoo-sales-offline-data-cache';

if (url.pathname === '/web/dataset/search_read') {

event.respondWith(

fetch(event.request.clone()).then((response) => {

if (response.status === 200) {

event.request.clone().json().then((payload) => {

if (payload.params && (payload.params.model === 'res.partner' || payload.params.model === 'product.product')) {

const cacheRequest = event.request.clone();

const cacheResponse = response.clone();

caches.open(DATA_CACHE_NAME).then((cache) => {

cache.put(cacheRequest, cacheResponse);

});

}

});

}

return response;

}).catch(() => {

return caches.match(event.request);

})

);

}

});

  


  ​I would appreciate any help or suggestions on how to solve this issue. Is there a better way to get the asset list from within the

  service worker? Or is there something I'm missing about how fetch works in this context?


  Thank you

0
Avatar
Kassér
Avatar
Nyan Min Htet
Forfatter Bedste svar

Thank You for your suggestion. I will try to approach with other point 

0
Avatar
Kassér
Avatar
Cybrosys Techno Solutions Pvt.Ltd
Bedste svar

Hi,


The root cause of your issue is that during the service worker’s install event, cache.addAll() fails if any asset URL isn’t publicly accessible. Some Odoo assets (like /web/content/...) require a logged-in session and return redirects or errors, so the fetch fails and breaks the whole install.


The solution is to avoid pre-caching restricted assets. Instead, pre-cache only public resources (like /web/assets/debug bundles, manifest, icons) and use runtime caching in the fetch event to store backend assets and API calls as they’re requested. This hybrid approach ensures the service worker installs cleanly while still giving offline support.


Hope it helps

0
Avatar
Kassér
Enjoying the discussion? Don't just read, join in!

Create an account today to enjoy exclusive features and engage with our awesome community!

Tilmeld dig
Related Posts Besvarelser Visninger Aktivitet
Remove/Disable "My Orders" button from mobile menu page for POS
webclient development sales shop
Avatar
Avatar
1
jul. 25
1123
Custom Cards Payment Module: POS Payment Summary Not Updating with Installments
javascript development sales project
Avatar
Avatar
2
feb. 25
2177
Help with Subscription Webhooks
webclient javascript development accounting debug
Avatar
Avatar
1
okt. 25
766
how to resolve (500 (INTERNAL SERVER ERROR) on login screen
javascript development configuration debug chrome
Avatar
Avatar
Avatar
3
sep. 25
1766
How can we unit test javascript components in web addons?
webclient javascript development v6.1 v7
Avatar
Avatar
1
mar. 15
8201
Community
  • Tutorials
  • Dokumentation
  • Forum
Open Source
  • Download
  • Github
  • Runbot
  • Oversættelser
Tjenester
  • Odoo.sh-hosting
  • Support
  • Opgradere
  • Individuelt tilpasset udvikling
  • Uddannelse
  • Find en bogholder
  • Find en partner
  • Bliv partner
Om os
  • Vores virksomhed
  • Brandaktiver
  • Kontakt os
  • Stillinger
  • Arrangementer
  • Podcast
  • Blog
  • Kunder
  • Juridiske dokumenter • Privatlivspolitik
  • Sikkerhedspolitik
الْعَرَبيّة Català 简体中文 繁體中文 (台灣) Čeština Dansk Nederlands English Suomi Français Deutsch हिंदी Bahasa Indonesia Italiano 日本語 한국어 (KR) Lietuvių kalba Język polski Português (BR) română русский язык Slovenský jazyk slovenščina Español (América Latina) Español ภาษาไทย Türkçe українська Tiếng Việt

Odoo er en samling open source-forretningsapps, der dækker alle dine virksomhedsbehov – lige fra CRM, e-handel og bogføring til lagerstyring, POS, projektledelse og meget mere.

Det unikke ved Odoo er, at systemet både er brugervenligt og fuldt integreret.

Website made with

Odoo Experience on YouTube

1. Use the live chat to ask your questions.
2. The operator answers within a few minutes.

Live support on Youtube
Watch now