DOM manipulation with PhantomJS

I use PhantomJS to create screenshots from arbitrary URLs. Before taking a screenshot, I want to manipulate the DOM page to remove all the drop-down menus, since PhantomJS does not display them correctly in the upper left corner of the page (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 great as standalone Javascript. However, it does not work inside the PhantomJS code, which I use to collect screenshots (the last part is 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 still display with the selected field in the wrong place. I would appreciate help in fixing the original PhantomJS rendering error or hiding the dropdown menus in the DOM. Thanks.

+8
dom phantomjs
source share
2 answers

Run it in the correct context, i.e. inside the page using page.evaluate . There are many examples included in PhantomJS that demonstrate this, for example. useragent.js .

+11
source share

Does this code not work? I used your cached selects variable in a for loop instead of reselecting 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"; } 
+2
source share

All Articles