当页面被history.pushState和ajax调用更改时插入内容脚本

2023-11-21

我遇到了将内容脚本插入到由history.pushState 和ajax 调用更改的页面中的问题。我找到了类似的话题在 stackoverflow,但该解决方案对我不起作用(该解决方案是使用 chrome.webNavigation.onHistoryStateUpdated 和“popstate”事件)。

这是我的清单的一个片段:

"content_scripts": [
    {
      "matches": ["https://vk.com/audios*", "https://vk.com/al_audio.php*"],
      "js": ["jquery-2.1.4.min.js", "getListOfSongs.js"]
    }
  ]

chrome.webNavigation.onHistoryStateUpdated仅当我导航到另一个页面,如果我按顺序多次导航到同一页面时才有效 什么都没发生。例如:它工作时

1) 前往https://vk.com/audios* - 首次打开页面或重新加载

2) 前往https://vk.com/some_other_page- 阿贾克斯调用

3) 前往https://vk.com/audios* - ajax调用

1) 前往https://vk.com/audios* - 首次打开页面或重新加载

2)再次转到https://vk.com/audios* - ajax 调用,此时内容脚本未注入
3)再次转到https://vk.com/audios* - ajax 调用,此时内容脚本未注入等

每次我第二次单击同一页面时,都会生成以下请求:

https://vk.com/al_audio.php?__query=audios*********&_ref=left_nav&_smt=音频%3A2&al=-1&al_id=********&_rndVer=60742

(请求的参数可能会有所不同)

Also JQuery .ajaxComplete在这种情况下没有捕获任何事件。

并且pushState不会触发“popstate”事件,所以我不能使用window.onpopstate事件

我可能会用chrome.webNavigation.onDOMContentLoaded and chrome.webNavigation.onCompleted但是当我重新加载页面时,这些事件会发生多次,因此脚本将被注入多次。

对于这种情况,最好的解决方案是什么?


我能想到的有两种可能的方法:

1 - 使用计时器检查您的脚本是否仍然存在,如果不存在,请重新添加...
2 - 检查 ajax 调用,如果它们的 url 与删除脚本的 url 之一匹配,请再次添加脚本。

您的脚本(清单中定义的脚本)仍然存在,即使在 ajax 调用之后,它也不会再次运行(不确定历史推送器会发生什么)。因此,我假设您需要重新添加一些元素或重新运行剥离。我假设您添加了附加 html 标签的脚本。

因此,您需要的是读取元素或重新运行特定代码的东西。


1 - 计时器方法 - 我创建了一个解决方案任何元素(不仅仅是脚本)我希望添加到某个目标元素在一个页面中。

它使用计时器来检查目标元素是否存在。 当它找到目标元素时,它会添加我的。然后调整计时器来检查我的元素是否仍然存在。如果没有,请重新添加。

你只需要打电话appendChildPersistent一次,这将在您导航的整个过程中保持活动状态。

var timers = {}; //stores the setInterval ids

//this is the only method you need to call
//give your script an `id` (1)
//the child is your script, it can be anything JQuery.append can take
//toElem is the Jquery "SELECTOR" of the element to add your script into.
//I'm not sure what would happen if toElem were not a string.
//callback is a function to call after insertion if desired, optional.
appendChildPersistent = function(id, child, toElem, callback)
{
    //wait for target element to appear
    withLateElement(toElem, function(target)
    {
        target.append(child); //appends the element - your script                                                                                                           
        if (typeof callback !== 'undefined') callback(); //execute callback if any

        //create a timer to constantly check if your script is still there
        timers[id] = setInterval(function()
        {                                       
            //if your script is not found, clear this timer and tries to add again          
            if (document.getElementById(id) === null)
            {
                clearInterval(timers[id]);
                delete timers[id];
                appendChildPersistent(id, child, toElem, callback);
            }
        },3000);

    });
}

//this function waits for an element to appear on the page
//since you can't foresee when an ajax call will finish
//selector is the jquery selector of the target element
//doAction is what to do when the element is found
function withLateElement(selector, doAction)
{   
    //checks to see if this element is already being waited for                             
    if (!(selector in timers))
    {
        //create a timer to check if the target element appeared                                                            
        timers[selector] = setInterval(function(){              
            var elem = $(selector);

            //checks if the element exists and is not undefined
            if (elem.length >= 0)
            {
                if (typeof elem[0] !== 'undefined')
                {
                    //stops searching for it and executes the action specified
                    clearInterval(timers[selector]);
                    delete timers[selector];
                    doAction(elem);
                }
            }
        }, 2000);
    }                                                           
}

(1) 看起来在脚本标签中添加Id没有问题:为脚本标签指定 ID


2 - 捕获ajax调用

一个选项是使用chrome.webRequest。但奇怪的是,这对我不起作用。另一种选择如下。

对于这种情况,请检查这个答案, and 别忘了阅读相关答案Chrome 扩展程序在那里。只有遵循整个过程,它才会起作用。幸运的是,我今天测试了它,效果很好:p

在这里,你要做的就是改变XMLHttpRequest方法open and send检测(也可能获取参数)它们何时被调用。

但是,在 Google 扩展中,您绝对有必要将片段插入页面中(不是注入内容脚本的后台页面或脚本,而是注入一些代码的内容脚本进入大教堂,如下所示)。

var script = document.createElement('script');
script.textContent = actualCode; //actual code is the code you want to inject, the one that replaces the ajax methods
document.head.appendChild(script); //make sure document.head is already loaded before doing it
script.parentNode.removeChild(script); //I'm not sure why the original answer linked removes the script after that, but I kept doing it in my solution

这一点至关重要,因为扩展程序试图创建一个隔离的环境,并且您对扩展程序所做的更改XMLHttpRequest在这种环境下根本不会参加。 (这就是为什么 JQuery.ajaxComplete 似乎不起作用,您需要在页面中注入一个脚本才能使其工作 -看这里)

In 这个纯javascript解决方案,您替换方法:

//enclosing the function in parentheses to avoid conflict with vars from the page scope
(function() {
    var XHR = XMLHttpRequest.prototype;

    // Store the orignal methods from the request
    var open = XHR.open;
    var send = XHR.send;

    // Create your own methods to replace those

    //this custom open stores the method requested (get or post) and the url of the request
    XHR.open = function(method, url) {
        this._method = method; //this field was invented here
        this._url = url; //this field was invented here
        return open.apply(this, arguments); //calls the original method without any change

        //what I did here was only to capture the method and the url information
    };


    //this custom send adds an event listener that fires whenever a request is complete/loaded
    XHR.send = function(postData) {
        //add event listener that fires when request loads
        this.addEventListener('load', function() {
            //what you want to do when a request is finished
            //check if your element is there and readd it if necessary
            //if you know the exact request url, you can put an if here, but it's not necessary

            addMyElementsToPage(); //your custom function to add elements
            console.log("The method called in this request was: " + this._method);
            console.log("The url of this request was: " + this._url);
            console.log("The data retrieved is: " + this.responseText);

        });

        //call the original send method without any change
        //so the page can continue it's execution
        return send.apply(this, arguments);

        //what we did here was to insert an interceptor of the success of a request and let the request continue normally
    };
})();
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

当页面被history.pushState和ajax调用更改时插入内容脚本 的相关文章

随机推荐

  • 如何告诉 Eclipse 使用与通常不同的 JRE 版本来编译和构建项目?

    我不确定这个问题是否已得到完整回答 或者我的标题是否足够描述我的情况 但我被要求将项目从使用 Ant 构建转换为 Maven 这部分还不错 但我被告知这个应用程序是专门为 JRE 1 5 版而不是我一直在处理的其他应用程序使用的 JRE 6
  • 为什么不使用 GlobalScope.launch?

    我读到了这个用法Globalscope非常沮丧 here 我有一个简单的用例 对于我收到的每条 kafka 消息 假设是一个 Id 列表 我必须将其拆分并同时为每个 Id 调用休息服务 并等待其完成并继续执行其他同步任务 该应用程序中没有其
  • 获取最后一个插入 ID 的标准方法是什么?

    获取最后插入的id的sql标准是什么 如果有这样的事情的话 mysql LAST INSERT ID postgresql 返回 f idmssql SCOPE IDENTITY 更多例子在这里 我的意思是 所有数据库都有不同的实现 这样的
  • AMQP C++ 实现 [关闭]

    Closed 此问题正在寻求书籍 工具 软件库等的推荐 不满足堆栈溢出指南 目前不接受答案 我们正在编写需要消息传递的 C 代码 是否有免费 开源且稳定的 AMQP 服务器可用 并且具有同样稳定的 C 客户端库 我们还需要向用户提供代码的
  • Xamarin.Forms - 用于异步操作的 BeginInvokeOnMainThread

    我熟悉有关使用 Device BeginInvokeOnMainThread 在 UI 线程上更新 UI 元素的规则 但是我有一个需要在 UI 线程上运行的操作 该操作实际上是一个任务 例如 XLabs Forms Mvvm 上的 Push
  • 如何停用 GMail 计量电子邮件?

    如何停用 google apps 脚本 活动报告 我尝试了gmail Meter 最后删除了google docs中的文档 现在 每天晚上我都会收到一份报告 如下 Ihr Skript Gmail Meter konnte nicht er
  • React - 如何在 Jest 中对 API 调用进行单元测试?

    我有一堆 API 调用 我想对其进行单元测试 据我所知 单元测试 API 调用并不涉及实际进行这些 API 调用 据我所知 您会模拟这些 API 调用的响应 然后测试 DOM 更改 但我目前正在努力做到这一点 我有以下代码 App js f
  • 在 SQL Server 上使用或不使用 CONSTRAINT 关键字的区别

    使用和不使用有什么区别CONSTRAINT在 SQL Server 上使用外键时的关键字 我注意到在这个特定情况下显然两者的工作原理相同 没有CONSTRAINT CREATE TABLE ClientsPhones ClientPhone
  • Freemarker 转义 freemarker

    我正在使用 freemarker 生成 freemarker 模板 但我需要一些方法来逃避 freemarker 标签 我该如何逃脱 lt list gt 标签或 expression 您还可以使用 expression 如果您发现 嵌套令
  • XML 模式如何通过枚举限制属性

    我有以下 XML 标签
  • 如何在C++中显示固定位数而不进行四舍五入

    我有这个代码 非常基本 include
  • d3.js:将数据从父节点传递到子节点

    我正在使用 d3 制作堆积条形图 数据是一个数组 每个栏都有一个对象 例如 喜欢 然后每个对象都包含一个值数组 这些值驱动每个条形的各个矩形 data key likes values key blue frog value 1 key g
  • 用“.”分割字符串(点)处理缩写时

    我发现这很难解释 所以我将首先举几个我想要实现的目标之前 之后的例子 输入示例 你好世界 这是一个测试 特警队 S W A T s w a t 2001 A 太空奥德赛 想要的输出 你好世界 这是一个测试 特警队 SWAT swat 200
  • 如何使 mailto 主题和正文在 gmail 等中工作?

    下午好 我有一个带有 mailto 链接的网站 用于向我母亲的公司发送电子邮件 非常标准的东西 我最近尝试添加一些其他位来获得标准主题和正文 当我使用 Outlook 在我的工作电脑上 时 它可以工作 但如果我使用自动打开 gmail 的家
  • 通过反射访问抽象类的属性

    我有一个抽象类 让我们命名它Base 该类包含一些属性 而且 我还有另一个类 继承自 classBase 让我们命名它Child Child并不抽象 我想从类访问属性Base与反射 和only中声明的那些属性Base 下面的代码当然是不可能
  • 为什么 NSMetadataQueryDidUpdateNotification 被快速连续调用多次?

    为了监控 iCloud 容器中的文件更改 我注册了 NSNotificationCenter defaultCenter addObserver self selector selector processiCloudUpdates nam
  • 如何使用 TypeScript 在 Material UI 上添加自定义颜色名称?

    我正在使用 TypeScript 使用 Material UI 并希望向我的主题添加自定义颜色 一切工作正常 除了 VSCode linter 向我显示下一条消息 Type tan string lightRed string red st
  • 具有现有数据库和自定义文件路径的 Android Sugar ORM

    我完全能够使用提供的示例来使用 Sugar ORM 在我的用例中 我从服务器下载 SQLite DB 它的 ETL 负载有数百万条记录 因此必须在服务器端完成 下载保存到内部存储上的自定义路径 就我而言 我不需要基于 POCO 的动态数据库
  • .NET 的 HTML 生成器?

    在过去几年使用 Seaside 后 我发现模板系统的代码味道很糟糕 是否有一个 net 框架使用类似于 Seaside 画布系统的东西来生成 html css 和 javascript 或者是一种避免我在模板中发现重复的方法 编辑 NHam
  • 当页面被history.pushState和ajax调用更改时插入内容脚本

    我遇到了将内容脚本插入到由history pushState 和ajax 调用更改的页面中的问题 我找到了类似的话题在 stackoverflow 但该解决方案对我不起作用 该解决方案是使用 chrome webNavigation onH