问题描述
TL; DR:我需要使用BrowserView中-usergesture-callback" rel ="nofollow noreferrer"> executeJavaScript
.该代码必须是类.如何对课程进行分类?
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');
// }
*/
但是我的问题是,如何对类进行字符串化?我需要使用new
从类创建的以下对象的字符串版本来注入它.
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}`);
这是我根据公认的答案最终实现它的方式:
Here is how I ended up implementing it based on the accepted answer:
view.webContents.executeJavaScript(
`window.person = new ${str}({ name: 'John' })`
);
推荐答案
您的问题中有解决方案.适用于函数的方法也适用于类.
You had the solution in your question.The same approach that works for functions works for classes too.
class Person {
constructor({ name }) {
this.getName = () => name;
}
}
const str = '' + Person;
console.log(str);
已更新,以响应有问题的其他数据.您无法序列化对象并使其跨越执行边界,因为该对象在那时不再是数据,而是在内存中运行.
Updated in response to additional data in question.You can't serialize an object and make it cross execution boundaries because it is no longer data at that point, but instead is running in memory.
您可以采取的一种方法是调用executeJavaScript
One approach you could take is invoke all of the code inside the call to executeJavaScript
例如:
view.webContents.executeJavaScript(`
class Person {
constructor({ name }) {
this.getName = () => name;
}
}
window.person = new Person({name: 'John'});
`);
或者
view.webContents.executeJavaScript(`
(function() {
class Person {
constructor({ name }) {
this.getName = () => name;
}
}
window.person = new Person({name: 'John'});
})();
`);
这篇关于JavaScript:调用new后如何对类进行字符串化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!