Search code examples
javascriptuserscripts

How find variable/array if I don't know full variable name in javascript


I am trying to get additional information from site and there is variable/array that defined randomly. Like this:

var firstvar_numbers= "already exist"
var secondvar_numbers= ["a","b","c","d"]

numbers is random value that given by site. In firefox DOM when I wrote half of secondvar_ it immediately find that I wanted because there is only one variable that starts with second. My question is how I can get value/array of variable in userscript/javascript by knowing part of the variable. Example if you don't understood: Html

//Variable that I need from server
<div id="variables" class="container">

<script type="text/javascript">
var exists_73647286="hello world"

var array_636353=[62,96,11,28]
</script>
</div>

Javascript

//Code that will get array
alert("exists_"+seconpartofvar())
function seconpartofvar(){your code}

OR

alert(autocomplate.exists_)

Here I can write alert(exists_) in Firefox console and it will recommend autocomplate.


Solution

  • Since it's declared with var on the top level, you can iterate over the properties of the window and find one which startsWith what you're looking for:

    // Example site code:
    var array_636353 = [62, 96, 11, 28];
    
    // Userscript code:
    const prop = Object.keys(window).find(key => key.startsWith('array_'));
    console.log(prop, window[prop]);