js如何获取当前页面所在的路径

JavaScript06

js如何获取当前页面所在的路径,第1张

可以使用window对象的location对象的里的href来获取当前页面的URL地址。

工具原料:编辑器、浏览器

1、Location 对象包含有关当前 URL 的信息,Location 对象是 Window 对象的一个部分,可通过 window.location 属性来访问,代码示例如下:

<html>

<head><script type="text/javascript">

<script>

alert(window.location.href) 

</script>

</script>

</head>

<body>

test

</body>

</html>

2、运行的结果如下图:

在开发过程中有时会遇到这种情况,需要调用js的一些方法,又不需要显示h5界面。比如,在你开发的产品中,PC、h5,移动端(Android、IOS)都需要使用到同一个算法,而且这个算法又非常的复杂,若每个端都写一边,不仅浪费时间,而且如果算法涉及到复杂的数字计算,那么就可能会导致每个端写出来的算法结果不一致。

所以这个时候,使用js编写一个通用算法是比较理想的一个解决方法,因为pc、h5、Android、ios都可以直接调用js代码,并执行计算结果。

Android调用本地js步骤:步骤一:在assets下添加你需要执行的js代码步骤二:Android代码 WebView mWebView = null

@Override protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState)

if (mWebView == null) {

initWebView()

}

getPrxResult()

}

/**

* 调用js方法

*/

private void getPrxResult(){

String e =""

String t =""

String url2 = "javascript:jclqBonusRange(" + e + "," + t + ")"//调用js方法

mWebView.loadUrl(url2) } /*** 初始化webview

*protected void initWebView() {

mWebView = new WebView(this)

mWebView.getSetting

使用javascript来获取当前url网址非常有用。下面以例子讲解:

输入的网址是(没有框架):http://localhost:81/Test/1.htm?Did=123

<br>以下为输出:

<br>

<SCRIPT>

//获取Url传过来的值

function Request(name)

{

new RegExp("(^|&)"+name+"=([^&]*)").exec(window.location.search.substr(1))

return RegExp.$2

}

thisURL = document.URL// http://localhost:81/Test/1.htm?Did=123

thisHREF = document.location.href// http://localhost:81/Test/1.htm?Did=123

thisSLoc = self.location.href // http://localhost:81/Test/1.htm?Did=123

thisDLoc = document.location // http://localhost:81/Test/1.htm?Did=123

thisTLoc = top.location.href // http://localhost:81/Test/1.htm?Did=123

thisPLoc = parent.document.location// http://localhost:81/Test/1.htm?Did=123

thisTHost = top.location.hostname// localhost

thisHost = location.hostname // localhost

thisU1 = window.location.protocol// http:

thisU2 = window.location.host // localhost:81

thisU3 = window.location.pathname// /Test/1.htm

document.writeln( thisURL + "<br />")

document.writeln( thisHREF + "<br />")

document.writeln( thisSLoc + "<br />")

document.writeln( thisDLoc + "<br />")

document.writeln( thisTLoc + "<br />")

document.writeln( thisPLoc + "<br />")

document.writeln( thisTHost + "<br />")

document.writeln( thisHost + "<br />")

document.writeln( thisU1 + "<br />")

document.writeln( thisU2 + "<br />")

document.writeln( thisU3 + "<br />")

document.writeln( "Did="+Request("Did") )// Did=123

</SCRIPT>