Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DOM manipulation with PhantomJS

Tags:

dom

phantomjs

I am using PhantomJS to create screenshots from arbitrary URLs. Before the screenshot is taken, I want to manipulate the page DOM to remove all drop-down menus, as PhantomJS renders them incorrectly in the top left-hand corner of the page (a known Phantom issue.)

I have a simple DOM script to do this with:

    var selects = document.getElementsByTagName('select');

    for (var i=0; i < selects.length; i++) {
        document.getElementsByTagName('select')[i].style.visibility="hidden";
    }

This has been tested and works fine as stand-alone Javascript. It doesn't however work inside the PhantomJS code I am using to collect the screenshots (last part shown):

  page.open(address, function (status) {

    if (status !== 'success') {
        console.log('Unable to load the address!');
    } else {
        window.setTimeout(function () {

            var selects = document.getElementsByTagName('select');

            for (var i=0; i < selects.length; i++) {
                document.getElementsByTagName('select')[i].style.visibility="hidden";
            }

            page.render(output);

            phantom.exit();

        }, 200);
    }
});

Some pages are still rendering with a select box in the wrong place. I'd appreciate help either solving the original PhantomJS rendering bug or hiding the drop-down menus in the DOM. Thanks.

like image 508
eli Avatar asked Aug 29 '12 14:08

eli


2 Answers

Run it in the right context, i.e. inside the page with page.evaluate. There are many examples included with PhantomJS which demonstrate this, e.g. useragent.js.

like image 51
Ariya Hidayat Avatar answered Oct 30 '22 22:10

Ariya Hidayat


This code doesn't work? I used your cached selects variable in the for loop instead of re-selecting the elements from the DOM to improve performance.

var selects = document.getElementsByTagName('select'); 
for (var i=0; i < selects.length; i++) { 
   selects[i].style.visibility="hidden"; 
}
like image 22
Cameron Tinker Avatar answered Oct 30 '22 20:10

Cameron Tinker