Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access URL query string in svelte

How should I access the the query string parameters from svelte? I'd like my script to behave differently when "?beta" has been appended to the URL.

My intuitive approach would be to use the standard URLSearchParams in a svelte #if block.

like image 255
Anna Avatar asked Mar 15 '21 12:03

Anna


3 Answers

Here's how you do it in Svelte Kit:

<script>
    import { page } from '$app/stores'
    const email = $page.url.searchParams('email')
</script>
like image 199
thomallen Avatar answered Oct 17 '22 22:10

thomallen


Yep, you should be able to use URLSearchParams. In general, anything you can do in plain JS you can do in a Svelte script tag.

<script>
    const urlParams = new URLSearchParams(window.location.search);
    const isBeta = urlParams.has('beta');
</script>

{#if isBeta}
    <p>This is beta!</p>
{:else}
    <p>This is not beta.</p>
{/if}

Edit: the above method will not work in SvelteKit, which enables server-side rendering by default. In SvelteKit, you should use the page store, which exposes a native URL object.

<script>
    import { page } from '$app/stores';
    
    const isBeta = $page.url.searchParams.has('beta');
</script>

This store was changed as recently as SvelteKit v1.0.0-next.208, so other answers referencing it may be out of date. In particular, $page.query is no longer available since it was replaced by $page.url.

like image 29
Geoff Rich Avatar answered Oct 17 '22 23:10

Geoff Rich


For anyone specifically using SvelteKit, a Svelte framework, the page store lets you import a page object allowing you to access the parameters as page.query:

<script>
  import { page } from '$app/stores';
  let isBeta = page.query.beta;
</script>


{#if isBeta}
  <p>This is beta!</p>
{:else}
  <p>This is not beta.</p>
{/if}
like image 10
cybermelon Avatar answered Oct 18 '22 00:10

cybermelon