When develop a wordpress plugin or work in wordpress theme, I usually meet the problem with getting URL in javascript code. The problem come is I want to get current URL of current page because not all situation we can pass the current URL from PHP code. That ‘s why I decide to share this tips to you to save our time.
It ‘s quite easy, just following this code
var currentPageUrl = ""; if (typeof this.href === "undefined") { currentPageUrl = document.location.toString().toLowerCase(); } else { currentPageUrl = this.href.toString().toLowerCase(); }
You may want to get it as a stand-alone function to put it in your javascript library, then let ‘s define it as blow:
function getCurrentURL(){ var currentPageUrl = ""; if (typeof this.href === "undefined") { currentPageUrl = document.location.toString().toLowerCase(); } else { currentPageUrl = this.href.toString().toLowerCase(); } return currentPageUrl; }
Now every time you want to get current URL, you just need to call getCurrentURL(). It ‘s quite easy to get current URL in javascritp! :).
Thanks for your visit and welcome your comment!