读取 js 链接后面的参数

读取 js 链接后面参数的逻辑

js/log.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
// 当前 script src 中的 js url
var jsUrl = document.scripts[document.scripts.length - 1].src;
console.log("url: %o", jsUrl);

var paramArr = jsUrl.split('\?');
console.log('paramArr: %o', paramArr);
if (paramArr.length === 1) {
return;
}
// 所有参数放到这个变量中
var map = {};

var keyValueStrArr = paramArr[1].split('\&');
console.log('keyValueStrArr: %o', keyValueStrArr);
for (var i = 0; i < keyValueStrArr.length; i++) {
var keyValueArr = keyValueStrArr[i].split('\=');
console.log('keyValueArr: %o', keyValueArr);
map[keyValueArr[0]] = keyValueArr[1];
}
console.log('map: %o', map);

在页面中引入js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<!doctype html>
<html lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=GBK"/>
<meta content="width=device-width,initial-scale=1.0,maximum-scale=1.0,user-scalable=no" name="viewport">
<meta content="yes" name="apple-mobile-web-app-capable">
<meta content="black" name="apple-mobile-web-app-status-bar-style">
<meta content="telephone=no" name="format-detection">
<meta content="email=no" name="format-detection">
<title>在用产品功能</title>
</head>
<body>
<h1>测试</h1>
<script src="js/log.js?v=20190124&timestamp=1234567"></script>
</html>

控制台打印

1
2
3
4
5
6
url: js/log.js?v=20190124&timestamp=1234567
paramArr: ["js/log.js", "v=20190124&timestamp=1234567"]
keyValueStrArr: ["v=20190124", "timestamp=1234567"]
keyValueArr: ["v", "20190124"]
keyValueArr: ["timestamp", "1234567"]
map: {"v": "20190124", "timestamp": "1234567"}
  • 本文作者: forever杨
  • 本文链接: https://blog.yl-online.top/posts/e053978f.html
  • 版权声明: 本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。如果文章内容对你有用,请记录到你的笔记中。本博客站点随时会停止服务,请不要收藏、转载!