How can I add query parameter(s) to the URL in Navigator.share() based on where its shared?

731 Views Asked by At

I'm using window.navigator.share({url}) . This makes it share the same url to all apps in the device.

Is it possible to add specific query parameter(I want to add utm parameters) for each app?

For example, if the user selected WhatsApp to share, then I can add the parameter ?utm_source=Whatsapp to the URL.

1

There are 1 best solutions below

2
On

You can use the URLSearchParams interface.

let url = new URL('https://example.com/some/path?foo=1&bar=2');
let params = new URLSearchParams(url.search.slice(1));

params.set('utm', 'whatsapp')

// params.toString() : "foo=1&bar=2&utm=whatsapp"
url.search = params.toString()

console.log(url.href)
// "https://example.com/some/path?foo=1&bar=2&utm=whatsapp"