当'#'在url中时,URLSearchParams无法获取第一个参数

时间:2018-02-28 23:42:41

标签: javascript

这似乎是此API中的一个错误,但我不知道在哪里报告它。所以我在这里发帖寻求帮助。 Mozilla docs URLSearchParams

如果window.location.href包含#,则URLSearchParams.get无法检索第一个搜索参数

const location = 'http://localhost:3000/path?referrer=https://google.com';
const myURL = new URL(location).searchParams.get('referrer')
// myURL === 'https://google.com

// in one line:
(new URL('http://localhost:3000/path?referrer=https://google.com')).searchParams.get('referrer')

但是稍微调整窗口位置的同样示例将失败

const location = 'http://localhost:3000/#/path?referrer=https://google.com';
const myURL = new URL(location).searchParams.get('referrer')
// myURL === null

// in one line
(new URL('http://localhost:3000/#/path?referrer=https://google.com')).searchParams.get('referrer')

此示例正在使用new URL(location).searchParams.get但如果您使用new URLSearchParams(...).get

调整它将产生完全相同的功能

3 个答案:

答案 0 :(得分:2)

在URL标准中,#引入了一个片段组件,该组件对传输协议没有特殊意义,并被视为辅助或用户指定的#34;语义被视为未知的信息。 URL中的#及其后面的所有内容都将传递给客户端应用程序(例如HTML浏览器),而无需解释。您可以使用window.location.hash在JavaScript中访问片段值。

任何URL参数必须位于片段标识符之前,否则它们将包含在片段内容中,而不会作为参数进行解析。

网址路径或参数中可以包含#,但需要将其转义为%23。我强烈建议不要为路径中包含#的静态内容编写路由器或创建服务器端文件夹,即使在技术上可行。

允许用户在表单输入中输入#通常会在提交表单之前使用encodeURIComponent()对输入值进行编码来自动处理。

使用特定MIME类型的明文制定的数据网址需要对文本中的任何#进行百分比转义,以避免截断由URL表示的数据。

答案 1 :(得分:0)

我知道这个问题有点老,但是最近我遇到了同样的问题,并创建了一个简单的函数来修复Url哈希和搜索参数:

function fixUrlHash(url) {
  let fixedUrl = new URL(url);
  let search = search;
  let hash = hash;
  const position = hash.indexOf('?');
  if(search.length <= 1 && position >= 0) {
    search = hash.substr(position);
    hash = hash.substr(0, position);
    fixedUrl.hash = hash;
    fixedUrl.search = search;
    fixedUrl.href = fixedUrl.toString();
  }
  return fixedUrl;
}

这仅返回带有固定哈希和搜索参数的新URL对象。获得固定的URL值后,如果原始URL是浏览器位置,则可以在浏览器中加载新的URL。

答案 2 :(得分:0)

只需将 # 替换为 /

let location = 'http://localhost:3000/#/path?referrer=https://google.com';
location = location.replace('#', '/');
let myURL = new URL(location).searchParams.get('referrer')
console.log(myURL)