0

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.

Yusifx1
  • 101
  • 1
  • 9
  • If varaibles are defiend in global scope, those will be under `window` object. `Object.keys(window)` will give you an array of all keys. you can then apply regular expression match on all keys to find out specific patterns. – Jimish Fotariya May 19 '20 at 20:25

1 Answers1

2

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]);
CertainPerformance
  • 356,069
  • 52
  • 309
  • 320
  • Nice! Do you know how to resolve the scoped variables? – M A Salman May 19 '20 at 20:26
  • @Yusifx1 `document.getElementById('#variables')` ? – CertainPerformance May 19 '20 at 20:33
  • 1
    @Supercool. For true access, you can use a MutationObserver to watch for the addition of the ` – CertainPerformance May 19 '20 at 20:37
  • If the site has multiple elements with the same ID, that's invalid HTML... but you can still iterate over the elements with the query string `[id="variables"]` - pass it to `querySelectorAll` and then you'll be able to iterate over them. – CertainPerformance May 19 '20 at 20:39
  • Final question. Should I get only variable from div or it wouldn't slow down browser/JavaScript/site if I use "window" with thousands variable? – Yusifx1 May 19 '20 at 20:40
  • @Yusifx1 A thousand operations isn't much on a modern computer, especially if you're just iterating over the properties of an object, even if it's the window object, that's quite cheap given modern computers. If you had to do it in a *tight loop*, on the other hand, that could be a problem, but that's rare. – CertainPerformance May 19 '20 at 20:42