Add workaround for `Function.toString()` to docs
See original GitHub issueLots of libraries rely on Function.toString()
to function, so I think it’s important to provide some sort of “hacky” solution to be able to use bytenode with the lib.
Ref: https://github.com/bytenode/bytenode/issues/93
Not only can you not use functions with puppeteer, but puppeteer now wraps all the string options (ex. waitForSelector("selector")
) in a function, then calls .toString()
on the wrapped function (or one that you’ve provided) before sending it to the browser
Ref: https://github.com/bytenode/bytenode/issues/34#issuecomment-807982226
Framework uses Function.toString()
to check if Function
is a class
As mentioned in https://github.com/bytenode/bytenode/issues/93#issuecomment-753661616 , a workaround could be just importing the function from a plain .js
file, and while this will work, it may be a little unnecessary and annoying at times
A simple fix that I’d like to propose to get added to the documentation (or at least a reference to this issue) is the ability to override .toString()
after bytenode breaks it
For example, to make a quick puppeteer fix:
const makeUnsafeFunction = (fnString) => {
const fn = new Function(fnString);
fn.toString = () => fnString;
return fn
}
const unsafeWaitForSelector = (selector, opts) => {
return page.waitForSelector(makeUnsafeFunction(`() => document.querySelector("${selector}")`), opts);
}
await unsafeWaitForSelector("#selector")
Or a fix for checking if a Function
is a class:
class YourClass {}
YourClass.toString = () => "class YourClass"
This is in hopes to save people’s time figuring out a good solution (because I know it would’ve saved mine 😅)
Issue Analytics
- State:
- Created 2 years ago
- Reactions:1
- Comments:8
Top GitHub Comments
Check here already a solution.
I think it could be relatively easy though considering how easy it is to parse and walk the js ast tree with modern packages Purely a guess so correct me if I’m wrong but if the cached code just relies on some offset/position from the source that it tries to lookup when calling
Function.prototype.toString
, it should be relatively easy to just move the function (or even just the necessary parts of it) to the position in the dummy code that v8 would look intoAnd to be honest, since this feature is ever so rarely actually needed, you could just get away with two comments, one that marks the start of the source that you want to be preserved and one at the end. Do some simple regex matching or even pure js splitting and move those parts to the dummy code