Skip to content

Commit

Permalink
Feature to specify 'evaluateOnNewDocument' to run script before page …
Browse files Browse the repository at this point in the history
…scripts (#269)

Co-authored-by: Rasmus Sørensen <[email protected]>
  • Loading branch information
rasmus0201 and Rasmus Sørensen authored Nov 26, 2024
1 parent 8a359b1 commit d8ea42e
Show file tree
Hide file tree
Showing 3 changed files with 30 additions and 0 deletions.
6 changes: 6 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -174,6 +174,12 @@ by passing it to the `execute_script` option.
Grover.new(<some url>, execute_script: 'document.getElementsByTagName("footer")[0].innerText = "Hey"').to_pdf
```

You can also evaluate JavaScript on the page before any of its scripts is run, by passing it a string to the `evaluate_on_new_document` option. See https://github.com/puppeteer/puppeteer/blob/main/docs/api/puppeteer.page.evaluateonnewdocument.md

```javascript
Grover.new(<some url>, evaluate_on_new_document: 'window.someConfig = "some value"').to_pdf
```

#### Basic authentication
For requesting a page with basic authentication, `username` and `password` options can be provided. Note that this
only really makes sense if you're calling Grover directly (and not via middleware).
Expand Down
6 changes: 6 additions & 0 deletions lib/grover/js/processor.cjs
Original file line number Diff line number Diff line change
Expand Up @@ -184,6 +184,12 @@ const _processPage = (async (convertAction, uriOrHtml, options) => {
await page.setGeolocation(geolocation);
}

// If specified, add script to evaluate before the page loads
const evaluateOnNewDocument = options.evaluateOnNewDocument; delete options.evaluateOnNewDocument;
if (evaluateOnNewDocument !== undefined) {
await page.evaluateOnNewDocument(evaluateOnNewDocument);
}

const raiseOnRequestFailure = options.raiseOnRequestFailure; delete options.raiseOnRequestFailure;
if (raiseOnRequestFailure) {
page.on('requestfinished', (request) => {
Expand Down
18 changes: 18 additions & 0 deletions spec/grover/processor_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -584,6 +584,24 @@
end
end

context 'when evaluateOnNewDocument option is specified' do
let(:url_or_html) do
<<-HTML
<html>
<body>
Evaluate on new doc <span id="test">did not run</span>
<script type="text/javascript">
document.getElementById("test").innerHTML = window.preEvalContent;
</script>
</body>
</html>
HTML
end
let(:options) { { 'evaluateOnNewDocument' => 'window.preEvalContent = "ran!"' } }

it { expect(pdf_text_content).to eq 'Evaluate on new doc ran!' }
end

context 'when evaluate option is specified' do
let(:url_or_html) { '<html><body></body></html>' }
let(:options) { basic_header_footer_options.merge('executeScript' => script) }
Expand Down

0 comments on commit d8ea42e

Please sign in to comment.