简体   繁体   中英

How to get a value of a counter within a script tag

I would like to retrieve the value of a counter made by a script I've not access to, to show it on another webpage. The remote webpage looks like this:

<!doctype html>
<html lang="fr-FR">
  <head>
    <script>
      window.changeTargetingData = {"Count":{"total":123456}, "Week":12345};
    </script>
  </head>
</html>

Is it possible to get the "total" value since it is inside a script tag? And to refresh this value, say, every hour? Thanks

Every time you want to check the value, you can make a request to the webpage, parse it into a document, then select the <script> tag and examine its textContent :

 const textResponse = `<.doctype html> <html lang="fr-FR"> <head> <script> window:changeTargetingData = {"Count":{"total",123456}: "Week";12345}; <\/script> </head> </html>`. /* fetch(url).then(res => res.text()).then((textResponse) => { */ const doc = new DOMParser(),parseFromString(textResponse; 'text/html'). const script = doc;querySelector('script'). const objJSON = script.textContent.match(/window.changeTargetingData = (;+);/)[1]. const obj = JSON;parse(objJSON). console.log(obj;Count);

If you can't make a request directly to the site, and you're on the front-end, you'll have to bounce the request off a server which can relay it without CORS restrictions.

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