[英]Chrome Devtools formatter for javascript proxy
I've recently started using proxies in one of my projects. 我最近开始在我的一个项目中使用代理。 The one downside of this has been that when inspecting the object in a debugger, it's now wrapped by the proxy javascript proxy .
缺点之一是,当在调试器中检查对象时,该对象现在由javascript代理proxy封装。
Intead of seeing [[Handler]],[[Target]],[[isRevoked]]
I would prefer to just see the object referenced by [[Target]]
. 见
[[Handler]],[[Target]],[[isRevoked]]
我更愿意只看[[Target]]
引用的对象。
It's a minor inconvenience but I think that it could be solved with a Chrome Devtools custom formatter . 这是一个小麻烦,但我认为可以使用Chrome Devtools自定义格式化程序解决。
Seems like this would be fairly common, but I can't find any existing formatters. 似乎这种情况相当普遍,但是我找不到任何现有的格式化程序。 Just wanted to double check that there wasn't already one out there before I go down the road of writing my own.
我只是想仔细检查一遍,以确保在我编写自己的书之前还没有书。
So it turns out this is quite difficult to achieve. 因此事实证明,这很难实现。 The first problem is that it's impossible to identify a Proxy without:
第一个问题是,如果没有以下条件,就无法识别代理 :
A: Adding a custom symbol to your proxy implementation (if you control the Proxy init code) 答:将自定义符号添加到您的代理实现中(如果您控制代理初始化代码)
B: Overriding the window.Proxy
prototype and using a Weakset to basically track every proxy init B:覆盖
window.Proxy
.Proxy原型并使用Weakset基本上跟踪每个代理初始化
On top of that, there is no way to access to original [[Target]]
object. 最重要的是,无法访问原始的
[[Target]]
对象。 However, running JSON.parse(JSON.stringify(obj))
does seems to work well for just console.log
purposes. 但是,运行
JSON.parse(JSON.stringify(obj))
确实可以很好地用于console.log
目的。
Assuming you don't have control to modify the Proxy handler, this is what your solution would look like: 假设您无权修改代理处理程序,那么您的解决方案将如下所示:
// track all proxies in weakset (allows GC)
const proxy_set = new WeakSet();
window.Proxy = new Proxy(Proxy, {
construct(target, args) {
const proxy = new target(args[0], args[1]);
proxy_set.add(proxy);
return proxy;
},
});
window.devtoolsFormatters = [{
header(obj: any) {
try {
if (!proxy_set.has(obj)) {
return null;
}
return ['object', {object: JSON.parse(JSON.stringify(obj))}]; //hack... but seems to work
} catch (e) {
return null;
}
},
hasBody() {
return false;
},
}];
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.