简体   繁体   中英

How can I read json content inside a <script> tag?

So when I want to put a Google +1 button on webpages, I would do this:

<script type="text/javascript" src="https://apis.google.com/js/plusone.js">
  {lang: 'zh-TW'}
</script>

But I am wondering, there is an object in the script tag, but it is also loading plusone.js ! At the end the script can also get the object inside the tag. How does Google do that? Unlike normally I would not put anything inside. Normally I would do

<script type"text/javascript" src="script.js"></script>

Since the URL is known, it's simple enough:

JSON.parse(
    document.querySelector("script[src='https://apis.google.com/js/plusone.js']")
        .innerHTML.replace(/^\s+|\s+$/g,'')
);

That said, as Alohci pointed out in the comments, the last script on the page will be the last one loaded when the script runs, because (unless specified otherwise) scripts are blocking. Therefore, this would work:

var scripts = document.getElementsByTagName('script');
var data = JSON.parse(scripts[scripts.length-1].innerHTML.replace(/^\s+|\s+$/g,''));

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