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.

1
  • 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. Commented May 19, 2020 at 20:25

1 Answer 1

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]);

Sign up to request clarification or add additional context in comments.

6 Comments

Nice! Do you know how to resolve the scoped variables?
@Yusifx1 document.getElementById('#variables') ?
@Supercool. For true access, you can use a MutationObserver to watch for the addition of the <script> tag and replace it with your own needed functionality: stackoverflow.com/a/59424277 If the variable stays constant, you can also use a regular expression to look through the textContent of the script tag and see what gets assigned to the variable
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.
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?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.