当ajax请求发生时运行代码的Chrome扩展

Chrome extension that runs code when ajax requests happen

本文关键字:代码 Chrome 扩展 运行 ajax 请求      更新时间:2023-09-26

因此,对我的问题进行基本描述。

我有一个扩展正在工作(终于),它将电话号码封装在一种类型的标签中。

它现在正在工作,但我对任何基于用户操作或基于ajax请求通过JS动态加载的内容都有问题

例如,如果我单击一封hotmail电子邮件并打开它,脚本就会工作,但只有当我刷新页面以便电子邮件加载并调用我的contentscript时,脚本才会工作。

我想过让用户点击扩展的图标来解决这个问题,但这并不是真正要求的功能。

如果Chrome中有一种方法可以监听ajax请求(似乎有)http://code.google.com/chrome/extensions/webRequest.html这就是我想做的,但我不确定如何实现这一点。我会把它当作听众吗?

我根据DOM的变化找到了另一种方法来实现这一点,但这使得加载需要很长时间,DOM中有太多事情要做。我需要监听AJAX请求,并在它们完成后再次运行我的代码。

任何帮助,甚至指向正确方向的指针都会很棒=)

如果这是一个愚蠢的问题,请注意,我保证我一直在谷歌上搜索表格以寻找答案,但似乎什么都找不到。我可能知道的不够多,甚至连正确的问题都问不出来。我已经使用javascript大约两周了。。。所以我的学习曲线一直很艰难。

当你说。。。

我根据DOM的变化找到了另一种方法,但这使得负载需要很长时间,只是发生了太多在DOM中这样做。我需要监听AJAX请求完成后再次运行我的代码。

你在哪里使用突变事件或突变观察员?因为我认为观察员在哪里可以解决这个问题。我以前从未使用过"观察者",并使用过"突变总结"。它似乎可以做你想做的事情,只是直到文档准备好/空闲时才开始观察(不确定是哪一个),所以你可能必须对准备好的文档进行扫描,然后解雇观察者
以下是我的测试代码(在内容脚本中)的样子。。。

handleChanges = function(summaries) {
    // There may be more things to ignore
    var ignore = {
        SCRIPT: true,
        NOSCRIPT: true, 
        CDATA: true,
        '#comment': true
    }
    summaries.forEach(function(summary) {
        summary.added.forEach(function(node) {
            if (!ignore[node.nodeName] || (node.parentNode && !ignore[node.parentNode.nodeName]) && node.nodeValue.trim()) {
                node.nodeValue='PAEz woz ere - '+node.nodeValue;
            }
        })
    })
}
var observer = new MutationSummary({
    callback: handleChanges,
    // required
    rootNode: document,
    // optional, defaults to window.document
    observeOwnChanges: false,
    // optional, defaults to false
    queries: [{
        characterData: true
    }]
});

检查XMLHttpRequest的另一种方法是劫持它,它看起来就像(在文档开始时的内容脚本中)。。。。。

function injectScript(source) {
    var elem = document.createElement("script"); //Create a new script element
    elem.type = "text/javascript"; //It's javascript
    elem.innerHTML = source; //Assign the source
    document.documentElement.appendChild(elem); //Inject it into the DOM
}
injectScript("("+(function() {
    function bindResponse(request, response) {
        request.__defineGetter__("responseText", function() {
            console.warn('Something tried to get the responseText');
            console.debug(response);
            return response;
        })
    }
    function processResponse(request,caller,method,path) {
        bindResponse(request, request.responseText);
    }
    var proxied = window.XMLHttpRequest.prototype.open;
    window.XMLHttpRequest.prototype.open = function(method, path, async) {
            var caller = arguments.callee.caller;
            this.addEventListener('readystatechange', function() {
                if (this.readyState === 4)
                    processResponse(this,caller,method,path);
            }, true);
        return proxied.apply(this, [].slice.call(arguments));
    };
}).toString()+")()");

这是我在超级棒的晚餐快乐博客上没有学到的
但正如您现在可能知道的,这对于ajax驱动的网站来说是不够的。通常情况下,你必须为网站写一些特定的东西,或者突变观察者可能会满足你的需求。

这是使用MutationObserver更新的答案,因为MutationSummary不再工作:

var observer = new MutationObserver(function(mutationsList) {
  console.log(`Something has changed`);
});
observer.observe(document.querySelector('.whatever'), {
  attributes: true,
  characterData: true,
  childList: true,
  subtree: true
});
  • 请确保将.whatever选择器更改为您感兴趣的任何类/id
  • 确保在subtree选项中指定true/false,以防您对选择器的子级修改感兴趣