TL;DR: I need to inject some JavaScript into a BrowserView
in Electron using executeJavaScript
. This code needs to be class. How can I stringify the class?
I found out that you can stringify functions using +
.
const fn = function() {
console.log('Hello');
};
const functionToText = '' + fn;
console.log(functionToText);
// function() {
// console.log('Hello');
// }
*/
But my problem is, how can you stringify classes? I need the string version of the following object created from the class with new
to inject it.
class Person {
constructor({ name }) {
this.getName = () => name;
}
}
const person = new Person({ name: 'John'});
const str = // somehow stringify person here
console.log(str);
// the person object
view.webContents.executeJavaScript(`window.person = ${str}`);
Edit:
Here is how I ended up implementing it based on the accepted answer:
view.webContents.executeJavaScript(
`window.person = new ${str}({ name: 'John' })`
);