简体   繁体   中英

upon entering/leaving the page append a string in the url. Is this possible?

Is there a way to append a string in the url upon leaving/entering?

Say the default url is www.foo.com

Then upon entering/leaving, it becomes www.foo.com?param=1 without clicking to something?

Just using javascript.

Any help would be much appreciated. Thanks!

Here is one possible method to do that. This is using jQuery, and only adds the parameter on page entry (on page leave, it's kind of pointless; also, that would trigger on addition for the first case as well) -

<script src="http://code.jquery.com/jquery-1.11.1.min.js"></script>
<script>
$( window ).load(function() {
        if (! window.location.href.contains("param=0")) {
                window.location.href = window.location.href+"?param=0";
        }
});
</script>

The easiest ways to do this would be to change document.location.search (which targets parameters) like this:



    if (document.location.search != ("?param=1")) {
        document.location.search = "?param=1";
    }

note that this essentially triggers a page reload though.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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