简体   繁体   中英

How can I load a DOM from a string in PhantomJS?

Most of the examples I have found on the web involve loading a URL.

However, if I simply have a string that contains an svg or html and I want to load it into a dom for manipulation, I cannot figure out how to manipulate it.

var fs=require('fs')
var content = fs.read("EarlierSavedPage.svg")
// How do I load content into a DOM?

I realize that, in this example where is a local file is being read, there is a workaround for reading the local file directly, but I am interested more generally in whether a page can be loaded from a string.

I have already looked at the documentation but did not see anything obvious.

The default page in PhantomJS is a comparable to about:blank and is essentially

<html>
    <body>
    </body>
</html>

It means that you can directly add your svg to the DOM to and render it. It seems that you have to render it asynchronously to give the browser time to actually compute the svg. Here is a complete script:

var page = require('webpage').create(),
    fs = require('fs')

var content = fs.read("EarlierSavedPage.svg")

page.evaluate(function(content){
    document.body.innerHTML = content;
}, content);

setTimeout(function(){
    page.render("EarlierSavedPage.png"); // render or do whatever
    phantom.exit();
}, 0); // phantomjs is single threaded so you need to do this asynchronously, but immediately

When you load an HTML file into content, then you can directly assign it to the current DOM (to page.content ):

page.content = content;

This would likely also need some asynchronous decoupling like above.

The other way would be to actually load the HTML file with page.open :

page.open(filePathToHtmlFile, function(success){
    // do something like render
    phantom.exit();
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM