Search code examples
javascriptphpworkbox

How to cache a dynamic URL - Workbox - Service Worker


I am trying to cache a dynamic URL.

It works fine like this:

workbox.routing.registerRoute(
  'https://www.testestest.com/?Q=Start',
  workbox.strategies.networkFirst({
      networkTimeoutSeconds: 3,
      cacheName: 'dynamicentry1',
      plugins: [
        new workbox.expiration.Plugin({
          maxEntries: 50,
        }),
      ],
  })
);

But if I want to get the dynamic content like this:

workbox.routing.registerRoute(
  'https://www.testestest.com/?Q=Start&testid=',
  workbox.strategies.networkFirst({
      networkTimeoutSeconds: 3,
      cacheName: 'dynamicentry1',
      plugins: [
        new workbox.expiration.Plugin({
          maxEntries: 50,
        }),
      ],
  })
);

If you click on https://www.testestest.com/?Q=Start&testid=1 that site should be cached - dynamically. How can I do that?

Thank you guys


Solution

  • You can set up a route using a regular expression instead of a string and get the sort of behavior that you're looking for. There's more information in the Workbox documentation at https://developers.google.com/web/tools/workbox/guides/route-requests#matching_a_route_with_a_regular_expression

    workbox.routing.registerRoute(
      new RegExp('/\\?Q=Start'),
      workbox.strategies.networkFirst({
          networkTimeoutSeconds: 3,
          cacheName: 'dynamicentry1',
          plugins: [
            new workbox.expiration.Plugin({
              maxEntries: 50,
            }),
          ],
      })
    );