Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Allow for JS scripts to be injected #46

Merged
merged 2 commits into from
Dec 31, 2016
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,7 @@ conversion({
},
fitToPage: false, //whether to set zoom if contents don't fit on the page
customHeaders: [],
injectJs: [], // injects javascript files in the page
settings: {
javascriptEnabled : true,
resourceTimeout: 1000
Expand Down
1 change: 1 addition & 0 deletions lib/conversion.js
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,7 @@ function convert(conversionOptions, cb) {
opt.settings = opt.settings || {};
opt.fitToPage = opt.fitToPage || false;
opt.waitForJSVarName = opt.waitForJSVarName || 'PHANTOM_HTML_TO_PDF_READY';
opt.injectJs = opt.injectJs || [];

if (opt.waitForJS && opt.settings.javascriptEnabled === false) {
throw new Error('can\'t use waitForJS option if settings.javascriptEnabled is not activated');
Expand Down
7 changes: 7 additions & 0 deletions lib/scripts/conversionScriptPart.js
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,13 @@ page.onError = function (msg, trace) {
};

page.onInitialized = function() {
if (body.injectJs && body.injectJs.length > 0) {
body.injectJs.forEach(function(script) {
console.log('Injecting ' + script);
page.injectJs(script);
});
}

// inject function to the page in order to the client can instruct the ending of its JS
if (body.waitForJS) {
page.evaluate(function(varName) {
Expand Down
1 change: 1 addition & 0 deletions test/injectjs.js
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
console.log('INJECTJS TEST');
15 changes: 15 additions & 0 deletions test/test.js
Original file line number Diff line number Diff line change
Expand Up @@ -223,6 +223,21 @@ describe("phantom html to pdf", function () {
done();
});
});

it('should allow to inject js files to the page', function(done) {
conversion({
html: 'foo',
injectJs: [
path.join(__dirname, 'injectjs.js')
]
}, function(err, res) {
if (err)
return done(err);

JSON.stringify(res.logs).should.containEql('INJECTJS TEST');
done();
})
});
}

rmDir = function (dirPath) {
Expand Down