从 Overlay JS 与页面 DOM 交互的安全方法
我有一个 Firefox 扩展,它可以检测浏览器中何时加载页面并返回其 window
和 document
。我想将一些事件(在我的插件覆盖层中启动功能)附加到页面中的元素,但我不知道如何以安全的方式执行此操作。
这是一个代码示例:
var myExt = {
onInit: function(){
var appcontent = document.getElementById("appcontent");
if(appcontent){
appcontent.addEventListener("DOMContentLoaded", this.onPageLoad, true);
}
},
onPageLoad: function(e){
var doc = e.originalTarget;
var win = doc.defaultView;
doc.getElementById("search").focus = function(){
/* ... 'Some privelliged code here' - unsafe? ... */
};
}
};
那么谁能告诉我添加这些事件/与页面的 DOM 交互的安全方法是什么?
提前致谢!
I have a Firefox extension that detects whenever a page loads in the browser and returns its window
and document
. I want to attach some events (that launch functions in my addon's overlay) to elements in the page, but I don't know how to do this in a way that's safe.
Here's a code sample:
var myExt = {
onInit: function(){
var appcontent = document.getElementById("appcontent");
if(appcontent){
appcontent.addEventListener("DOMContentLoaded", this.onPageLoad, true);
}
},
onPageLoad: function(e){
var doc = e.originalTarget;
var win = doc.defaultView;
doc.getElementById("search").focus = function(){
/* ... 'Some privelliged code here' - unsafe? ... */
};
}
};
So can anyone tell me what's the safe way to add these events/interact with the page's DOM?
Thanks in advance!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
![扫码二维码加入Web技术交流群](/public/img/jiaqun_03.jpg)
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我认为您想要监听
focus
事件,而不是替换focus()
函数:通常,这里很少会出现问题,因为您没有访问直接页面 - 已经有一个 安全层 (这也是为什么替换
focus ()
方法将不起作用)。您还可以确保仅对“真实”事件而不是网页生成的事件进行操作,您可以像示例代码中那样检查event.isTrusted
。但只要您不解开对象或运行从网站获得的代码,您就应该是安全的。I think that you want to listen to the
focus
event, not replace thefocus()
function:Usually, there is fairly little that can go wrong here because you are not accessing the page directly - there is already a security layer (which is also why replacing the
focus()
method will have no effect). You can also make sure that you only act on "real" events and not events that have been generated by the webpage, you checkevent.isTrusted
for that like in the example code. But as long as you don't unwrap objects or run code that you got from the website, you should be safe.