How to get the variable defined inside a – abdullahDev Feb 06 '21 at 06:18

  • @costaparas I'm building a chrome extension. The website has some data defined inside a script tag that I want access to. – abdullahDev Feb 06 '21 at 06:20
  • @abdullahDev If they made it global (as in your posted code) then you can access it globally. If they did not, you can't do anything else about it. – FZs Feb 06 '21 at 06:23
  • @abdullahDev In that case, you will want to take a look at [this related post](https://stackoverflow.com/questions/3955803/chrome-extension-get-page-variables-in-content-script). – costaparas Feb 06 '21 at 06:24
  • 2 Answers2

    1

    You can access the object stored in the variable by using the variable name.

    const data = {'a': 1, 'b': 2};
    console.log(data); //logs the object
    

    You can access the properties of the object using dot or square bracket notation

    //dot notation
    console.log(data.a); // 1
    
    //square bracket notation
    console.log(data["b"]);// 2
    
    Stephenio
    • 11
    • 3
    • Sorry, maybe I didn't clarify I can't do that. I'm building a chrome extension and I only have page source. – abdullahDev Feb 06 '21 at 06:22
    • @abdullahDev What are you trying to do with the object ? – Stephenio Feb 06 '21 at 06:25
    • I'm building a chrome extension, that runs a content script when I visit website X. Inside the source of the website, there is a script tag, that has an ID and an object variable. I want to get that variable. – abdullahDev Feb 06 '21 at 06:28
    • @Stephenio OP wants to read the values in a script on the page, but due to the fact that Chrome extensions exist in a separate context, it's impossible to simply read the variables in like you're doing in your answer - they're like two different webpages. – Jack Bashford Feb 06 '21 at 06:28
    0

    Many good methods can be found here. But if you don't want to mess around with inserting scripts and reading values back via less intended methods (and potentially if you're slightly mad) you could use eval:

    eval(document.getElementById("myscript").innerHTML);
    console.log(data["a"]); // 1
    

    I do not recommend doing this, it's only used as a simple method that works in the case you've described. I would highly recommend using methods found here instead.

    Jack Bashford
    • 43,180
    • 11
    • 50
    • 79