使用jQuery在页面加载时将字符串添加到url?

use*_*820 7 javascript url jquery

我正在尝试在页面加载时将此特定字符串添加到我的URL的末尾:

?aa_campaign = f45632

(http://examplesite.com/test.html)

它用于营销和跟踪.

我试过这个:

if window.location.href.indexOf("http://examplesite.com/test.html") {
  window.location = "http://examplesite.com/test.html?aa_campaign=f45632";
}
Run Code Online (Sandbox Code Playgroud)

直接上升不起作用,但这个想法是我正在寻找的.有什么想法吗?

Ped*_*ito 9

没有必要jQuery,你可以JavaScript在大多数"现代"浏览器中使用纯粹的,即:

if (window.location.href  === "http://examplesite.com/test.html") {
    window.history.pushState("object or string", "Title", "http://examplesite.com/test.html?aa_campaign=f45632");
}
Run Code Online (Sandbox Code Playgroud)

pushState()方法

pushState()接受三个参数:状态对象,标题(当前被忽略)和(可选)URL.让我们更详细地研究这三个参数中的每一个:

state object — The state object is a JavaScript object which is associated with the new history entry created by pushState(). Whenever
Run Code Online (Sandbox Code Playgroud)

用户导航到新状态,触发popstate事件,并且事件的state属性包含历史记录条目的状态对象的副本.

The state object can be anything that can be serialized. Because Firefox saves state objects to the user's disk so they can be restored
Run Code Online (Sandbox Code Playgroud)

在用户重新启动浏览器之后,我们在状态对象的序列化表示上强加了640k字符的大小限制.如果将序列化表示形式大于this的状态对象传递给pushState(),则该方法将引发异常.如果您需要更多空间,建议您使用sessionStorage和/或localStorage.

title — Firefox currently ignores this parameter, although it may use it in the future. Passing the empty string here should be safe
Run Code Online (Sandbox Code Playgroud)

反对未来对方法的改变.或者,您可以为您要移动的州通过一个简短的标题.

URL — The new history entry's URL is given by this parameter. Note that the browser won't attempt to load this URL after a call to
Run Code Online (Sandbox Code Playgroud)

pushState(),但稍后可能会尝试加载URL,例如在用户重新启动浏览器之后.新URL不一定是绝对的; 如果是相对的,则相对于当前URL进行解析.新URL必须与当前URL的源相同; 否则,pushState()将抛出异常.此参数是可选的; 如果未指定,则将其设置为文档的当前URL.

SRC:https://developer.mozilla.org/en-US/docs/Web/Guide/API/DOM/Manipulating_the_browser_history