微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

我正在尝试在页面加载时将此特定字符串添加到我的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";
}

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

解决方法

不需要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");
}

pushState()方法

pushState() takes three parameters: a state object,a title (which is
currently ignored),and (optionally) a URL. Let’s examine each of
these three parameters in more detail:

06001

the user navigates to the new state,a popstate event is fired,and
the state property of the event contains a copy of the history entry’s
state object.

06002

after the user restarts the browser,we impose a size limit of 640k
characters on the serialized representation of a state object. If you
pass a state object whose serialized representation is larger than
this to pushState(),the method will throw an exception. If you need
more space than this,you’re encouraged to use sessionStorage and/or
localStorage.

06003

against future changes to the method. Alternatively,you Could pass a
short title for the state to which you’re moving.

06004

pushState(),but it might attempt to load the URL later,for instance
after the user restarts the browser. The new URL does not need to be
absolute; if it’s relative,it’s resolved relative to the current URL.
The new URL must be of the same origin as the current URL; otherwise,
pushState() will throw an exception. This parameter is optional; if it
isn’t specified,it’s set to the document’s current URL.

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

原文地址:https://www.jb51.cc/jquery/158833.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐