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

So when I want to put the Google +1 button on web pages, I would do the following:

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

But I wonder if there is an object in the script tag, but it also loads plusone.js ! At the end of the script, you can also get the object inside the tag. How does google do this? Unlike usual, I would not put anything inside. I usually did

 <script type"text/javascript" src="script.js"></script> 
+4
source share
1 answer

Since the URL is known, it is quite simple:

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

However, as Alohchi noted in the comments, the last script on the page will be the last to load when the script starts, because (unless otherwise specified) the scripts are blocked. Therefore, this will work:

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

All Articles