如何在闪电组件 salesforce 中获取查询字符串参数

how do I get the query string parameters in lightning component salesforce

我正在尝试从当前页面获取 url 查询字符串参数,我有以下代码:

doInit: function (component, event, helper) {
    var urlParams = new URLSearchParams(window.location.search);
    console.log("params::: ", urlParams);
    if (urlParams.has("openSidebar") && urlParams.get("openSidebar") == true) {
      console.log("redirection happening....");

      component.set("v.showFeed", true);
      component.set("v.isSidebarOpen", true);
    }
  },

出于某种原因,我似乎无法使用此行 var urlParams = new URLSearchParams(window.location.search); 我不知道为什么。

是否有任何替代方法或 salesforce 方法可以从 url 获取查询字符串参数?

我基本上一无所获,执行似乎停在我使用 URLSearchParams!

的那一行

也很想知道为什么在这种情况下闪电不让普通 javascript 执行?

URLSearchParams() 也不能在我的浏览器上运行,但我想出了一个辅助函数来完成这项工作。

function getURLSearchParameters() {
  const urlSearchParameters = {};
  let searchParameters = decodeURIComponent(window.location.search);
  if (searchParameters !== '') {
    searchParameters = searchParameters.substring(1).split('&'); // get ride of '?'
    for (let i = 0; i < searchParameters.length; i++) {
      [key, value] = searchParameters[i].split('=');
      urlSearchParameters[key] = value;
    }
  }
  return urlSearchParameters;
}

很遗憾,我无法回答您的其他问题,因为我没有任何使用 salesforce 的经验

使用 new URLSearchParams 将 return 一个 class 的实例,而不是对象(或映射)。

您可以使用此代码将 key/pair 值转换为对象。然后您可以检查对象上的值:

const searchParams = new URLSearchParams('?openSidebar=true&foo=bar&test=hello%26world')
const params = [...searchParams.entries()].reduce((a, [k, v]) => (a[k] = v, a), {})
console.log(params)


if (params.openSidebar === 'true') {
  console.log("redirection happening....");
  // do stuff here      
}

Note, we use === 'true' since the url parameter will always be a type of string.

既然你说它不起作用,你可以构建自己的解析器:

const qs = '?openSidebar=true&foo=bar&test=hello%26world'
  .slice(1) // remove '?'

const d = decodeURIComponent // used to make it shorter, replace d with decodeURIComponent if you want
const params = qs
  .split('&') // split string into key/pair
  .map(s => s.split('=')) // split key/pair to key and pair
  .reduce((a, [k, v]) => ((a[d(k)] = d(v)), a), {}) // set each object prop name to k, and value to v

console.log(params)

Note, we use decodeURIComponent() (or shorthand d()) last, because the parameters may contain ampersands or equals signs. Should we call d() first, we would split on these characters, which we don't want to happen.