Search code examples
javascripttypescriptdeep-linking

How to build Universal url using js?


Currently, I use Firebase deep link, And now I don't want to use Firebase anymore, so I need to implement deep link by myself,

What can I do?


Solution

  • You didn't specify a platform, but in browser, URL class is part of the browser API.

    You can use it to alter URLs or parse them, for example:

      const test = new URL("http://example.net");
      console.log(test.href) // http://example.net/
      test.protocol = "https";
      console.log(test.href); // https://example.net/
      test.pathname = "myfile.html";
      console.log(test.href); // https://example.net/myfile.html
    

    It does require you to specify some valid URL as a starting point though, but you can then change every part of it to whatever you need.

    For example, if you wanted to get an absolute link to another file on your domain on frontend, you could do:

    var url = new URL(location);
    url.pathname = "anotherfile.html"
    url.hash = "someanchor"
    console.log(url.href) // https://stackoverflow.com/anotherfile.html#someanchor