【问题标题】:Notification/Hook on document/window change通知/挂钩文档/窗口更改
【发布时间】:2012-12-25 08:04:30
【问题描述】:

我想编写一个浏览器扩展程序,它会在某些事件发生时执行某些操作,我想知道是否已经有这样的 API(Firefox 或 Chrome)。

我最感兴趣的是 DOM 变化和窗口变化。

让我们考虑这个例子:

<html>
<head>
<script type="text/javascript">
    function addContentToDocument(content){
        document.cookie = "debug=true"; //<--- Notify

        if(content != null){
            document.write(content); //<--- Notify
        };
    }
</script>
</head>

<body onload="addContentToDocument('Say cheese')">
<h3>My Content</h3>
</body>
</html>

因此,在这个简单的示例中,我将对 2 个事件感兴趣:document.cookie 更改和 document.write 方法调用。当这些事情发生时,我希望在我的分机中得到通知。 不是这些语句是否存在于可用的 javascript 上下文中,而是它们是否实际正在执行。

我尝试在 Firefox 扩展和 Chrome 扩展中搜索 API,但找不到任何有用的东西。

谢谢。

UPDATE:我感兴趣的其他方法是调用 eval() 方法和 localStorage 修改

【问题讨论】:

    标签: javascript google-chrome-extension firefox-addon google-chrome-devtools firefox-addon-sdk


    【解决方案1】:

    当前的 Firefox(和 Chrome,带有 webkit 前缀)支持 Mutation Observers。我不认为你可以用它来捕获 cookie 更改,但你绝对可以捕获对 DOM 所做的更改(无论是否使用 document.write)。

    Mozilla 文档中的示例:

    // select the target node
    var target = document.querySelector('#some-id');
    
    // create an observer instance
    var observer = new MutationObserver(function(mutations) {
      mutations.forEach(function(mutation) {
        console.log(mutation.type);
      });    
    });
    
    // configuration of the observer:
    var config = { attributes: true, childList: true, characterData: true }
    
    // pass in the target node, as well as the observer options
    observer.observe(target, config);
    
    // later, you can stop observing
    observer.disconnect();
    

    【讨论】:

    • 调用修改localStorage怎么样?还是调用 eval() 方法?
    • 我其实从来没有用过这些方法,我只知道它们存在。但我相信它们仅适用于 DOM 突变。对于eval,您可以使用var originalEval = eval; eval = function(){} 之类的内容覆盖它。你也可以用 localStorage 方法做类似的事情。
    • 对于本地存储,您可以只使用发送到窗口对象的事件。像:window.addEventListener("storage", function() { console.log('storage'); }, false); 会这样做。
    【解决方案2】:

    如果您想监视在选项卡/窗口中打开的文档的更改,那么 MutationObservers 就是这样做的方法。如果你想监控纯 JS 中调用的方法,你需要查看 Spidermonkey 的 JSEngine api,尤其是关于 profiling & tracking 的 api:

    https://developer.mozilla.org/en-US/docs/SpiderMonkey/JSAPI_User_Guide#Tracing_and_Profiling

    【讨论】:

      猜你喜欢
      • 2023-04-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-02-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多