在页面上显示URL的一部分(即Instagram访问令牌)


Display part of URL on a page (i.e. Instagram Access Token)?

我想要实现的是,当用户使用Instagram进行身份验证时,他们会被重定向到像"http://domainnamehere./instagram#access_token=27744335.fcaef44 "这样的页面。a95s9e741f3c4ea7bcad21d80809ca40 "

能够打印"27744335.fcaef44."A95s9e741f3c4ea7bcad21d80809ca40"字符串在网页的一部分,即<p>Here is your access token: ________</p>

我知道如何使用javascript打印整个URL,使用这个:<h3 id="right"><script type="text/javascript">document.write(location.href);</script></h3>

但是我如何设置它只获取部分URL呢?

确切地说,我想要实现的可以在这里看到直播http://theultralinx.com/instagram(点击"设置instagram,"认证,然后下一页显示访问令牌。

谢谢!

您仍然可以查找URI解析器,但是可以使用indexOfsubstring等基本字符串函数获得,如下所示:

var uri = "http://domainnamehere./instagram#access_token=27744335.fcaef44.a95s9e741f3c4ea7bcad21d80809ca40";
var indexOfHashVar = uri.indexOf("access_token=");
// 13 is the number of characters of "access_token="
var token = uri.substring(indexOfHashVar + 13);
console.log(token);

正如@PhistucK在一些评论中建议的那样,您可能会使用window.location.hash获得整个uri的哈希部分,因此我的示例可能会在第一行更改为:

var uri = window.location.hash;

永远不要使用document.write,不鼓励使用。这应该可以工作。

HTML——

<p>Here is your access token: <span id="access-token"></span></p>
JavaScript——

window.addEventListener("load", function () {
 // Getting the part of the URL that starts with #.
 var hash = document.location.hash,
     // Storing the string for which we search in the hash.
     accessTokenParameter = "access_token=";
 // Setting the found value as the content of the access-token element we created
 // above by taking the part of the hash (substring) that begins after the
 // parameter by getting the index of the character (indexOf) with which the
 // parameter name starts and adding the length of the parameter name (and =)
 // in order to get past the name and start from the value.
 document.getElementById("access-token").innerHTML =
  hash.substring(hash.indexOf(accessTokenParameter) +
   accessTokenParameter.length);
}, false);

为了支持ie浏览器,您可以使用window.onload =或命名函数,并在特征检测后使用window.attachEvent

<h3 id="right">
<script type="text/javascript">document.write(window.location.hash.split("access_token=")[1]);  </script>
</h3>

你可以使用

<h3 id="right">  <script type="text/javascript"> var href = location.href; href = href.replace("http://domainnamehere./instagram#access_token=","");  document.write(href);  </script>  </h3>

如果你的链接总是像问题中的链接(相同的域&没有其他变量)你可以使用这个:

var url =location.href ;
var res = url.slice(45);
console.log(res);