The PWA manifest should have its start_url set to the present current_url

I am working on a Progressive Web App (PWA) and I have a 'manifest.json' file. I am looking for a way to automatically set the manifest's 'start_url' as the current URL when users install the app. Is there a method to achieve this?

It is important to note that in my PWA, each user has a unique URL to their account. Therefore, when they install the PWA, the 'start_url' should be set to their current URL, such as https://example.com/user/id=abc1322112.

I have attempted to modify the manifest using script.js but without success.

Answer №1

It's not possible to directly modify the URL in the manifest file, but a workaround is to assign a dummy URL that can be redirected by the service worker.

Manifest:

{
  "start_url": "/user/me"
}

Service worker:

self.addEventListener("fetch", event => {
  const url = new URL(event.request.url);
  if (url.pathname === "/user/me") {
    const userId = /* retrieve user id */;
    const newUrl = `/user/id=${userId}`;
    // Redirect to the correct URL
    const response = new Response(null, { status: 302, headers: { Location: newUrl } });
  } else {
    // For all other cases, fetch from the network as usual
    event.respondWith(fetch(event.request));
  }
});

Answer №2

<script>
const manifest = {
  name: 'My New Application',
  short_name: 'New App',
  display: 'fullscreen',
  theme_color: '#000000',
  background_color: '#f1f1f1',
  icons: [
    { src: `${window.location.origin}/new-icon-192x192.png`, sizes: '192x192', type: 'image/png' },
  ],
  start_url: window.location.href
};
const link = document.createElement('link');
link.rel = 'manifest';
link.href = `data:application/json;base64,${btoa(JSON.stringify(manifest))}`;
document.head.appendChild(link);
</script>

For those in need, this script is functional.

Delete your existing manifest.json file and insert this script into your JavaScript or HTML code. Remember to replace your current icon with "new-icon-192x192.png"

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

JavaScript for returning a boolean output

I have been tasked with creating a webpage based on the requirements below Here is the current code that I am working with function validate() { var form = document.getElementsByTagName('form')[0]; if (form.tickets.value <= form.childr ...

Extracting decimal numbers from JSON data

I am currently facing an issue in my Angular project where I am attempting to read a JSON file. This file is stored in the assets folder and contains decimal values such as: { "valueA": 0.40000000000002, "valueB": 23.999999999999999 ...

How can I assign a variable to a JSON value with spaces in its name?

I have a variable let importantData = data[selectedItem].attributes[0]; I need to link it to various information within a JSON dataset in order to retrieve the value when I execute the following code, everything works smoothly let electricityPlant = u ...

Utilizing external imports in webpack (dynamic importing at runtime)

This is a unique thought that crossed my mind today, and after not finding much information on it, I decided to share some unusual cases and how I personally resolved them. If you have a better solution, please feel free to comment, but in the meantime, th ...

No reply from Axios after using async await

Here's a simple method that utilizes Axios to make a call to an API. Interestingly, when the method is called, it doesn't display any output, no logs or error messages. async deActivate(product: Product): Promise<void> { try { ...

Swapping out a Django template variable for a variable generated using JavaScript

I'm new to Django and Javascript (less than 3 weeks!) and I have a query that may seem naive, so any assistance would be appreciated. In my current code, I have an HTML table rendered with the following snippet: <table border="1" class="dataframe ...

Directories odejs ode_packages pminary ode_packages pminary pm-cli.js’

Encountering this frustrating Node.js issue on my Windows system has been a common occurrence for me: npm --version node:internal/modules/cjs/loader:1093 throw err; ^ Error: Cannot find module 'C:\Program Files\nodejs\node_modules& ...

Issue: retrieving a value from a JSON dataset using PHP

Here is the JSON data from pincodes.json file: [{ "officename": "Netajinagar B.O", "pincode": 744207, "taluk": "Hut Bay", "districtname": "South Andaman", "statename": "ANDAMAN \u0026 NICOBAR ISLANDS" }, { "officename": "Tushn ...

Tips for creating a useRef element

Greetings! I have implemented a horizontal stack with images and added navigation buttons on each end for scrolling. Here is the code snippet: const PostDetails = props => { let scrl = useRef(null); const [scrollX, ...

What's the issue with reducers receiving a Function instead of an Object in Redux?

I encountered an error in my react and redux project but I am unable to figure out how to fix it. Here is the error message: The reducer received unexpected type "Function" as the previous state. It was expecting an object with keys: "posts", "sidebar" ...

Tips for executing a function on a specific class selector using the document.getElementsByClassName method

When I click on a specific class, I want to implement a fade-out function in JavaScript. However, I am struggling to make a particular class fade out successfully. I attempted to use the this keyword, but it seems like I might be using it incorrectly bec ...

What is the process for modifying information within a text document?

What I am trying to achieve is a ticker with two buttons that can increment or decrement the value by one each time they are clicked. In addition, I want this value to be synced with a number stored in a text file. For instance, if both the counter and t ...

The ul cannot be hidden if there are no li elements within it

Currently, I am attempting to hide the unordered list (ul) on a specific page using AJAX due to certain sections of the site being Ajax-based. <ul class="sub-nav-20-m" id="filtersList_m"> </ul> Below is the code that I hav ...

tips for storing user input into an array

I am currently developing a calculator that uses Json data. The goal is to retrieve the Grid Code associated with a specific longitude and latitude input. However, I am encountering an issue where the result returned is 0, indicating that the value of the ...

When I utilize $router.push() to navigate to a different page, the back button will take me back to the previous page

Within my Vue project, there is an HTML page that I am working on. Here is the link to the page: https://i.sstatic.net/cbtqM.png Whenever I click on the "+"" button, it redirects me to this specific page: https://i.sstatic.net/0rmMD.png This page funct ...

Image cannot be shown on HTML webpage

There seems to be an issue with the rendering of the image on the index.html page. All the necessary files, including index.html, app.js, and the image file are located in a virtual machine (VM). After successfully logging in with login.js, the page redire ...

Regular expression for AWS S3 bucket naming conventions

I'm currently facing an issue while attempting to create an s3 bucket using cloudformation. Despite using the regex ^([0-9a-z.-]){3,63}$, it appears that invalid patterns like "..." and "---" are being accepted, which do not align with the new s3 nami ...

Have you tried incorporating Nostramap Javascript into your vue.js projects?

Instructions on Using Nostramap API to Call a Map. Refer to the following example: ...

The information returned to the callback function in Angular comes back null

In my Node.js application, I have set up an endpoint like this: usersRoute.get('/get', function(req, res) { //If no date was passed in - just use today's date var date = req.query.date || dateFormat(new Date(), 'yyyy-mm-dd&ap ...

Changing HTML lists into JSON format

I am facing a slight issue with my HTML template while trying to convert it to JSON. My goal is to convert a list of HTML messages into JSON format. I appreciate your assistance in advance. HTML Template <div class="message"> <div class="mes ...