简体   繁体   English

如何检查Referrer URL是否有URL参数?

[英]How to check if Referrer URL has URL parameters?

I'd like to check if my Referrer URL has parameters in it.我想检查我的 Referrer URL 中是否有参数。 Because based on this I'd like to change the url of a button to a different page.因为基于此,我想将按钮的 url 更改为不同的页面。

What I have now:我现在所拥有的:

var referrer = document.referrer;
var referrerparams = referrer.search;

if (referrerparams) {
 > 'script to change urlbutton.href'
}

So I thought i could use both document.referrer and window.location.search, to see if the referrer URL has parameters in it.所以我想我可以同时使用 document.referrer 和 window.location.search,来查看引用 URL 中是否有参数。 Independently these two work fine, but not together.这两个独立工作正常,但不能一起工作。 I get the following in console: ƒ search() { [native code] } .我在控制台中得到以下内容: ƒ search() { [native code] }

Does anyoneone know how to check if the Referrer URL has parameters?有谁知道如何检查Referrer URL 是否有参数? It doesn't even matter what parameters, just if they exit.甚至什么参数都无关紧要,只要它们退出即可。

You can create a URL object from the referrer and check its search property.您可以从引用创建一个URL对象并检查其search属性。

const referrerQueryParamStr = new URL(document.referrer).search

if (referrerQueryParamStr) {
    // change urlbutton.href
}

If you want the individual key-value pairs in an easy-to-use format, you can use the searchParams property instead:如果您希望单个键值对采用易于使用的格式,则可以改用searchParams属性:

const referrerQueryParams = new URL(document.referrer).searchParams

for (const [key, val] of referrerQueryParams) {
    console.log({ key, val })
}

I get the following in console: ƒ search() { [native code] } .我在控制台中得到以下内容: ƒ search() { [native code] }

This is because document.referrer is just a string before you convert it.这是因为document.referrer在转换之前只是一个字符串。 What you're logging is actually the String#search function.您记录的实际上是String#search函数。

typeof document.referrer // string
typeof document.referrer.search // function
document.referrer.search === String.prototype.search // true

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM