3

I'm trying to run an IMacros macro written in javascript on a webpage, like so:

for (var i = 1; i < 18; i++) {
   document.querySelector(".foo table > tbody > tr:nth-child(" + i + ") > .goo:nth-child(2) > a").click();
   document.querySelector(".foo > a").click();

if (i % 17===0) {
    alert('Reset i');
    i = 1;
    }
}

Everything seems to work fine from the js console, but when I run the macro, I get:

"ReferenceError: document is not defined, line 2 (Error code: -991)"

I've loaded JQuery into iMacros with this, and put my code between:

$(document).ready(function () {
    //
}); 

But I keep getting this error if I use JQuery:

TypeError: $ is not a function, line 28 (Error code: -991)

And if I only use JS, I get the same 'document is not defined' error as before.

So my question is, do I need to define the document, and how do I do it?

Community
  • 1
  • 1
Andratwiro
  • 655
  • 1
  • 5
  • 11

1 Answers1

7

I've never been able to load jQuery into an imacros script, but that's not such a big deal in the end. To access the DOM you need to refer each element as: window.content.document.getElementsByClassName('foo') for example. This will give you an array so be sure to pick each of the elements in the array you need:

var foo_class = window.content.document.getElementsByClassName('foo');

for (i=0;i<foo_class.length;i++){
//do something
}

Hope it helps

EDIT to add working example:

var links = window.content.document.getElementsByClassName('question-hyperlink');
var list=[]
for (i=0;i<links.length;i++){ 
txt=links[i].innerHTML;
list.push(txt);
}
number=links.length;
linkstexts=list.toString();
showme="number of links with class=question-hyperlink: "+number+"       text links with class=question-hyperlink: "+linkstexts;

iimDisplay((showme))

Copy the code in a macro.js and run it in firefox on stackexchage. It will count all the links with the class="question-hyperlink" and will display their respective text - you can see it in the green textbox under Play(Loop) button.

flish
  • 596
  • 1
  • 6
  • 17
  • What are u using to run this code? FireBug console? – edinvnode Jun 10 '14 at 16:49
  • no, a .js script run directly in imacros for firefox. i'm not at the pc right now and it's rather late where i live, but tomorrow i'll post a working script that counts links or whatever. – flish Jun 10 '14 at 20:18