2020-03-06 | UNLOCK

利用URLSearchParams獲取URL Query參數 更新網址

Initialise

1
const params = new URLSearchParams(window.location.search);

Update url history (change current url)

1
window.history.replaceState({}, '', `${window.location.pathname}?${params}`);

獲取URL Query (get)

假設url query為?foo1=bar1&foo2=bar2

1
2
3
const params = new URLSearchParams(window.location.search);
params.get('foo1'); // "bar1"
console.log(params.toString()); // "foo1=bar1&foo2=bar2" 就是?之後的部分

更新URL Query (set, append, delete)

假設url query為?foo1=bar1&foo2=bar2

1
2
3
4
5
6
7
8
9
const params = new URLSearchParams(window.location.search);
params.set('foo1','abc'); // replace the original value
console.log(params.toString()); // "foo1=abc&foo2=bar2"
params.append('foo1','def'); // add a new value
console.log(params.toString()); // "foo1=abc&foo2=bar2&foo1=def"
params.get('foo1'); // 'abc'
params.getAll('foo1'); // ['abc','def']
params.delete('foo2'); //delete a key
console.log(params.toString()); // "foo1=abc&foo1=def"

這時會發現console.log雖然打印出正確的值,網址列卻沒更新,以下代碼可以更新網址列

1
window.history.replaceState({}, '', `${window.location.pathname}?${params}`);

合起來就是

1
2
3
const params = new URLSearchParams(window.location.search);
params.set('foo1','abc');
window.history.replaceState({}, '', `${window.location.pathname}?${params}`);

新的url query為?foo1=abc&foo2=bar2

在React中於頁面加載時讀取URL Query

1
2
3
4
5
6
7
8
9
10
import { useEffect } from 'react';

function myApp (){
useEffect ( () => {
if(window.location.search){
const searchParams = new URLSearchParams(window.location.search);
doSomething (searchParams.get('foo1')); // do something
}
},[]); // this empty array is a trick to make useEffect to run only once when the page mounted
}

Reference

  1. URLSearchParams: Mozilla 文檔
  2. window.history.replaceState: Google Developers 文檔
  3. useEffect: React 官方文檔

評論加載中