Robert Guice
Robert Guice

Reputation: 659

With PhatomJS can you inject CSS to page.content?

With PhantomJS, I'm having trouble rendering screenshots of external pages using flex. As a workaround, I'd like to add some CSS to the page.content of the opened page.

Is this possible?

I'm missing some foundational knowledge because I'm getting errors with everything I tried.

$file = 'screenshot.png';

var webPage = require('webpage');
var page = webPage.create();

page.open('http://phantomjs.org', function (status) {
  var content = page.content;

  *** content.add-css-to-header***

  page.render('".$file."'); //Rendered with my CSS flexbox fix.
  phantom.exit();
});

I'd expect it to update the html code, render the page (w/flexbox fixed) and take a screenshot to look as it does with a normal browser.

Upvotes: 1

Views: 230

Answers (2)

Louis Mitchell
Louis Mitchell

Reputation: 1

If you have no way around using it still, even though it's unsupported, this should work:

page.open('http://phantomjs.org', function (status) {
      
  page.evaluate(function() {
    document.getElementById('flexbox-wrap').style.display = 'flex'; // edit element directly
    document.querySelector('body').classList.add('flexbox-fix'); // add a class for existing CSS to be rendered 
  });
        
  page.render('".$file."'); //Rendered with my CSS flexbox fix.
  phantom.exit();

});

Upvotes: 0

Vaviloff
Vaviloff

Reputation: 16856

Unfortunately, PhantomJS's rendering engine is very obsolete and the project itself is discontinued. Currently the best alternative to migrate to from PhantomJS is puppeteer which uses the latest Chromium for rendering pages. It is maitained by Google itself and is now being actively developed.

Upvotes: 0

Related Questions