Normally I would do it with
await page.evaluateOnNewDocument(my_js_code);
where my_js_code is something like:
Object.defineProperty(HTMLCanvasElement.prototype, "toBlob", ...
But the problem is that after that the code becomes visible
console.log(HTMLCanvasElement.prototype.toBlob.toString());
With the native function the code is not visible, toString returns [native code]
, not the actual code
So, is there a way I can override a function at a deeper level with Pupeteer?
The problem is actually not with puppeteer, try running your code in a chrome repl (it will give the same result). Object.defineProperty
doesn't accept a value as third argument, but a "descriptor". I am guessing you put the function right there in the third argument like
Object.defineProperty(HTMLCanvasElement.prototype, "toBlob", () => {
console.log('toBlob!');
});
but it wants it like this
Object.defineProperty(HTMLCanvasElement.prototype, "toBlob", {
value: () => {
console.log('toBlob!');
}
});
Example code that worked for me: https://gist.github.com/dralletje/37d0fc8a564ad377d60881d7c7429f6b
Native code means it's implemented in the browser, possibly in a language other than Javascript. When you supply the function body, it won't be native code but the function you defined.
I don't think there is a way to define code that the devtools console would output as native code, and even if there was one it would only obfuscate what it does and could not hide it.
So I found out that this seems to sort of "emulate" the native function behaviour:
Object.defineProperty(HTMLCanvasElement.prototype.toBlob, "toString", {
"value": function () {
return 'function toBlob() { [native code] }';
}
});
Not sure if there are any side effects tho
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With