Page has a script loaded with <script>
tag containing the following code:
window._test = "test",
function () {
"use strict";
function foo() {
console.log("foo()");
return "foo"
}
console.log("start");
var a = foo();
}()
I want to override foo()
function inside that anonymous function with another function, e.g.:
function bar() {
console.log("bar()");
return "bar"
}
One way is to enable debugger and pause execution at var a = foo();
and set foo = bar
. But such way requires manual actions.
I want to do this automatically. Basically in Puppeteer or Selenium. After opening page, once script loaded - immediately override that function.
In the normal case, you couldn't do it, because:
foo
is entirely private to the function it's defined in.But #2 there brings us to...
I want to do this automatically. Basically in Puppeteer or Selenium.
Puppeteer lets you intercept requests, so you could intercept the request for the file that this code appears in and do a search and replace on that code before it's executed.
I've never done it, but it looks fairly straightforward. Roughly:
const puppeteer = require("puppeteer");
(async () => {
const browser = await puppeteer.launch();
const page = await browser.newPage();
await page.setRequestInterception(true);
page.on("request", (interceptedRequest) => {
if (interceptedRequest.isInterceptResolutionHandled()) {
return;
}
if (interceptedRequest.url().includes("the-relevant-filename")) {
// ...read the original file, do your search-and-replace,
// then...
interceptedRequest.respond(/*...your updated file text...*/);
} else {
interceptedRequest.continue();
}
});
await page.goto("https://example.com");
await browser.close();
})();
That's completely untested, but you get the idea.
In a comment you've said:
yes, but script may have checksum protection
True! But you can intercept the request for the file that loads the script and replace (or remove) the checksum. ;-)