如何处理传入的URL请求只使用浏览器js?



我想从URL获取信息。

示例:mywesite.com/#base64text

如何使用浏览器js获取传入请求。在js中使用哪个函数

如果您需要做的只是提取标签符号之后的数据,那么只需像这样使用.split()location.href:

const data = location.href.split('#', 2)[1];

如果你需要更进一步,在URL中存储JS对象,那么你应该使用base64编码的JSON。要生成编码数据并将其放入URL中,只需使用JSON.stringify()atob():

const obj = {
name: 'Bob',
age: 30,
};
location.href += '#' + btoa(JSON.stringify(obj));
// the page will now reload with the data stored in the URL

然后,解码数据,使用atob()JSON.parse():

const urlData = location.href.split('#', 2)[1];
const data = urlData ? JSON.parse(atob(urlData)) : null;
console.log(data);
// returns any data stored in URL, or null