Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to override native function with Puppeteer

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?

like image 206
Alex Avatar asked Sep 09 '20 18:09

Alex


3 Answers

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

like image 110
Michiel Dral Avatar answered Sep 24 '22 23:09

Michiel Dral


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.

like image 41
Tamás Sallai Avatar answered Sep 22 '22 23:09

Tamás Sallai


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

like image 42
Alex Avatar answered Sep 24 '22 23:09

Alex