0

I am using Tampermonkey to get an element that was previously created with javascript. The code used to create the element looks like this:

a = document.getElementById("iframe").contentDocument.createElement("canvas")

I tried

var canvas = document.getElementById("iframe").contentDocument.getElementsByTagName("canvas")[0];

and this:

var canvas = document.getElementsByTagName("canvas")[0];

Since I don't know the exact timing the element is created, I used an asynchronous loop

for (var i = 0; i<2000; i++){
    setTimeout(function(){
        var canvas = document.getElementById("iframe").contentDocument.getElementsByTagName("canvas")[0];
        if (typeof canvas !== 'undefined') {
            console.log("HAS CANVAS");
            console.log(i);
        }else{
            console.log("UNDEFINED");
        }
    },1);
}

but this always returns undefined.

Any idea how I could get the canvas element reference once it is created?

Herr
  • 33
  • 4

1 Answers1

0

I used an asynchronous loop

It is not really asynchronous loop. You've just created 2000 timeouts, which will be executed as soon as possible, because timeout value is 1.

I think in your case intervals are suitable.

var intervalId = setInterval(function(){
    var canvas = document.getElementById("iframe").contentDocument.getElementsByTagName("canvas")[0];
    if (typeof canvas !== 'undefined') {
        console.log("HAS CANVAS");
        console.log(i);
        clearInterval(intervalId);
    }else{
        console.log("UNDEFINED");
    }
}, 1000);

It will check for canvas once in a second (1000 ms), untill finds one.

Andrey
  • 4,020
  • 21
  • 35
  • hmm, strange. It doesn't detect canvas. Here is the website I am trying to analyze http://www.browserleaks.com/canvas. – Herr May 17 '16 at 10:03