从 Overlay JS 与页面 DOM 交互的安全方法

发布于 2024-12-03 10:23:53 字数 710 浏览 1 评论 0原文

我有一个 Firefox 扩展,它可以检测浏览器中何时加载页面并返回其 windowdocument。我想将一些事件(在我的插件覆盖层中启动功能)附加到页面中的元素,但我不知道如何以安全的方式执行此操作。

这是一个代码示例:

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技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

萌吟 2024-12-10 10:23:53

我认为您想要监听 focus 事件,而不是替换 focus() 函数:

doc.getElementById("search").addEventListener("focus", function(event)
{
  if (!event.isTrusted)
    return;

  ...
}, false);

通常,这里很少会出现问题,因为您没有访问直接页面 - 已经有一个 安全层 (这也是为什么替换 focus () 方法将不起作用)。您还可以确保仅对“真实”事件而不是网页生成的事件进行操作,您可以像示例代码中那样检查 event.isTrusted 。但只要您不解开对象或运行从网站获得的代码,您就应该是安全的。

I think that you want to listen to the focus event, not replace the focus() function:

doc.getElementById("search").addEventListener("focus", function(event)
{
  if (!event.isTrusted)
    return;

  ...
}, false);

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 check event.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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文