拦截video.js xhr调用并修改xhr响应

时间:2018-09-12 21:34:25

标签: javascript asynchronous xmlhttprequest video.js

我有一种有效的方法来拦截xhr调用并修改video.js xhr响应。但是有问题。

我修改video.js xhr响应的解决方法是

  1. 我修改了主要的xhr原型,并将异步函数添加到“ readystatechange ”事件监听器中
  2. 我的自定义异步功能被触发。此自定义功能可以进行多个promise xhr调用,并加入内容,并将video.js xhr响应替换为我的自定义响应。

    (function (proxied) {
            XMLHttpRequest = function () {
    
            //cannot use apply directly since we want a 'new' version
            var wrapped = new (Function.prototype.bind.apply(proxied, arguments));
    
            // Here we can subscribe to the xhr.send to save the xhr events to local variable, remove the events from xhr
    
            // ---------------- Add custom onreadystatechange event so we will be able to modify the response --------------
            wrapped.addEventListener("readystatechange", async function () {
    
                    console.log(this.readyState);
    
                    // When download completed
                    if (this.readyState === 4) {
    
                        console.log(this.onreadystatechange);
    
                        var customContent = await GetCustomContent();
    
                        // Update the value of the response object
                        Object.defineProperty(this, 'response', {
                            value: customContent,
                            writable: false
                        });
    
                        // Update the value of the response text
                        Object.defineProperty(this, 'responseText', {
                            value: customContent,
                            writable: false
                        });
    
                        // As we have successfully modify the response now we can add back the events to the xhr and trigger it here.
    
                    }
    
                    //this.responseText = "Customized response";
    
                }, false);
    
                // -----------------------------------------------------------------------------------------------------------
    
            return wrapped;
        };
    })(XMLHttpRequest);
    

我面临的问题

随着video.js xhr调用将其on功能注册到事件“ readystatechange ”。当我添加自己的函数时,我的函数会先被调用。但是由于我的函数在运行过程中具有灵活性,因此触发了video.js xhr事件函数,因此修改响应没有任何效果。

所以我认为如果我们列出xhr请求的“ readystatechange”事件,将它们保存到本地变量,然后当我的asy函数promise返回时,我们将存储在本地变量中的事件加回来然后触发它。

这样,我们将能够修改响应,然后触发video.js事件。

但是我不知道如何将事件存储在变量上,将其从xhr中删除,然后再次添加回xhr中(如果可能)。你能告诉我我该怎么做吗?

我在头脑中有上述变通办法来修改响应,如果您有更好的方法,请告诉我。

谢谢!

0 个答案:

没有答案
相关问题