phantomjs doesn't show rendered page - phantomjs

I am newbie with phantomjs and trying to figure out how it works. I take this example
var page = require('webpage').create();
console.log('test');
page.open('https://github.com/', function() {
page.render('github.png');
phantom.exit();
});
put to the file and execute
./phantomjs phantomjs-2.0.0-macosx/examples/github.js
Output is
test
and nothing more. What I need is some pdf file with rendered page.

Try setting the viewportSize and adding more detail to the render function
var webPage = require('webpage');
var page = webPage.create();
page.viewportSize = { width: 1920, height: 1080 };
page.open("https://github.com", function start(status) {
page.render('github.pdf', {format: 'pdf', quality: '100'});
phantom.exit();
});

Related

How to display a PDF generated with express/pdfkit in browser from api-endpoint

I generate a pdf with with express and pdfkit like:
router.get("/create_pdf", (req, res) => {
var foo = req.body.foo;
var bar = req.body.bar;
// query Postgres with foo and bar to get some custom values
//create pdf
const doc = new PDFDocument();
doc.pipe(res);
doc.fontSize(25).text("Just a header", 100, 80);
// build some more stuff depending of Postgres query
doc.end();
})
My frontend using vue receives the response
print: function() {
data = {foo: "foo", bar: "bar"};
this.axios({
method: "get",
url: "get_recipe_as_pdf",
data: data,
})
.then((response) => {
console.log(response);
window.open(response.data);
})
.catch(() => {
//some error
});
},
The console shows data: "%PDF-1.3↵%����↵7 0 obj↵<...
window.open(...) opens a blank tab.
I found similar questions but could not find an answer. I probably have some understanding problems, so I'd appreciate a hint. Thanks.
In your express app: res.setHeader('Content-Type', 'application/pdf');
In your frontend just open the link "manually" like clicking on an anchor: click me
The pdf should open in a new tab if your browser supports that, else it will be downloaded.
Edit: for clarification: window.open expects a url as first parameter, not the content of a pdf.

Interacting with iframe with empty src attribute

I'm trying to test an a page with an external component which contains a following iframe:
<iframe id="iframe1" src="about:blank" ... >
This iframe has an empty body initially but is populated with content after some actions.
When trying to run the following piece of code:
.expect(myIFrameSelector().visible).ok()
.switchToIframe(myIFrameSelector())
.expect(firstRowSelector()).eql("Hello")
I receive the following error on line 3:
The content of the iframe in which the test is currently operating did not load.
I tried waiting for the contents to appear with wait() and I checked it with debug() too.
Any ideas what could be the problem?
I assume that this is because the content was probably populated using JS, so can I somehow tell testcafe that the content is actually ready?
You can try to wait and check if the document in the iframe is loaded using ClientFunction.
For example:
import { Selector, ClientFunction } from 'testcafe';
const waitForIframeLoad = ClientFunction((iframeSelector) => new Promise((resolve, reject) => {
var i = 0;
var intervalId = null;
intervalId = window.setInterval(() => {
var iframeElement = document.querySelector(iframeSelector);
if (iframeElement
&& iframeElement.contentWindow
&& iframeElement.contentWindow.location.href !== 'about:blank'
&& iframeElement.contentDocument) {
window.clearInterval(intervalId);
resolve();
}
if (i > 60) {
window.clearInterval(intervalId);
reject(new Error('Iframe content loading timeout'))
}
i++;
}, 1000);
}));
fixture`fixture`
.page`http://example.com`;
test('test', async t => {
const iframeSelector = '#simulatorFrame';
await waitForIframeLoad(iframeSelector);
await t
.switchToIframe(iframeSelector)
.click(Selector('button'));
});

How to test content of iFrame using jest

I want to test content of the iFrame Tag using jest.
For e.g I have a small html file that shows google homepage in iframe.
I want to test that google homepage is coming in iFrame or not.
<!DOCTYPE html>
<html>
<body>
<h2>Google</h2>
<iframe src="http://www.google.com" style="border:none;"></iframe>
</body>
</html>
can someone suggest me that how can I test that iframe using jest ?
Thanks in Advance.
const fs = require('fs');
const path = require('path');
const html = fs.readFileSync(path.resolve(__dirname, './index.html'), 'utf8'); //--> get the file content
describe('Iframe Test Suit', function () {
beforeEach(() => {
document.body.innerHTML = html.toString();
});
it('Should load iframe content', function (done) {
const iframe = document.querySelector("iframe"); //--> get the iframe element
expect(iframe).toBeTruthy();
onLoad();
function onLoad() {
const iframeContent = iframe.contentDocument || iframe.contentWindow.document;
if (iframeContent.readyState == "complete") {
const input = iframeContent.querySelector("input");
expect(input).toBeTruthy();
done();
} else {
setTimeout(() => onLoad(), 100); //--> call again if iframe content is not loaded
}
}
});
});
By default, jsdom will not load any sub-resources like iframes. To load such resources you can pass the resources: "usable" option, which will load all usable resources.
jest.config.js
"testEnvironmentOptions": { "resources": "usable" }

PhantomJS page.includeJs Not Working

I want to create sample script to login at my website.
My script like this :
var page = require("webpage").create();
var system = require("system");
var data = {
"username": system.args[1],
"password": system.args[2]
}
function login(data){
page.open("http://localhost/mywebsite/login.php", function(){
page.includeJs("https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js", function(){
console.log("Come in here.");
phantom.exit();
)}
)}
}
login(data);
When I run phantomjs in terminal, example : phantomjs myscript.js admin admin
i dont get anything in my terminal.
what's wrong in my code?
The way you closing callbacks is wrong. you are closing like this )}.it should be });
Your code here
var page = require("webpage").create();
var system = require("system");
var data = {
"username": system.args[1],
"password": system.args[2]
}
function login(data){
page.open("http://localhost/mywebsite/login.php", function(){
page.includeJs("https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js", function(){
console.log("Come in here.");
phantom.exit();
});
})
}
login(data);

in phantomjs,how to pass variables from page context to outside the page context

consider the following snippet.how can i access the value of the page url outside the page context?globally accessing the value was not working either.callbacks wasn't clear to me in approach.
page.onUrlChanged = function(targetUrl) {
console.log('New URL: ' + targetUrl);
};
page.onConsoleMessage = function (msg) {
console.log(msg);
};
var abc=page.open(url,function(status){
page.evaluate(function(){
//some code;
})
return page.url;
});
console.log(abc);
the code always gives undefined page url.
PhantomJS documents are very much recommended: http://phantomjs.org/api/webpage/method/evaluate.html
page.open(url,function(status){
var current_url = page.evaluate(function(){
return document.location.href;
})
console.log(current_url);
});