Jackmc1047 Jackmc1047 - 3 months ago 21
AngularJS Question

How to access JSON data in script tag using jQuery in a bookmarklet

I'm writing a bookmarklet that injects jQuery and then tries to access certain data on a webpage. The page uses AngularJS. The JSON data I want can be seen in a script tag when clicking view source in Chrome.

<script type="text/json" class="menu-page-data" page="0">
/* The JSON data */
</script>


I'm unable to access this data though with
JSON.parse($('.menu-page-data').html())
.

How can a bookmarklet parse this JSON?

Answer

Guided by @DG., the following code works to get the text inside the <script> tag and parse it as JSON.

$.get(document.location.href).done(function (htmlText) {
    var scriptClassIndex = htmlText.indexOf('menu-page-data');
    var scriptSubStr = htmlText.substring(scriptClassIndex);
    var scriptEndIndex = scriptSubStr.indexOf('</script>');

    var justScript = scriptSubStr.substring(0, scriptEndIndex);
    justScript = justScript.replace('menu-page-data" page="0">', '');
    justScript = justScript.trim();
    var jsonData = jQuery.parseJSON(justScript);
});