如何在加载URL后才调用revokeObjectURL?

时间:2015-08-24 11:03:35

标签: javascript google-chrome pdf onload revokeobjecturl

我有一个网络应用程序。它在谷歌浏览器中运行,不需要在任何其他浏览器中运行。

我有PDF数据,它已在服务器上生成并在AJAX请求中发送回客户端。 我从PDF数据创建一个blob。 我使用window.URL.createObjectURL从blob创建一个URL,然后将其加载到一个窗口(我的preview_window)中,该窗口之前已经创建以显示PDF。

要加载网址,我设置了preview_window.location.href。

我想调用revokeObjectURL以避免在窗口中生成和预览新PDF时浪费越来越多的资源。 问题是在设置preview_window.location.href后立即调用它太快了,并阻止显示PDF。所以我只想在加载URL后调用revokeObjectURL。 我已经尝试将preview_window.onload设置为回调用于此目的,但它永远不会被调用。

我想知道:

  1. 当窗口加载了URL时是否可以触发回调,正如我试图做的那样?怎么样?
  2. 是否有其他方法可以确保及时调用revokeObjectURL?
  3. 如果我在窗口完成加载URL时无法触发revokeObjectURL,我可能会在生成新URL之前立即撤销每个URL。但是如果可能的话,我宁愿在加载后立即撤销URL。

    我准备了一个html文件,可以很好地演示这种情况:

    <html>
        <head>
            <title>Show PDF Demo</title>
            <script>
                var build_blob = function(mime_type, data) {
                    var buf = new ArrayBuffer(data.length);
                    var ia = new Uint8Array(buf);
                    for (var i = 0; i < data.length; i++) ia[i] = data.charCodeAt(i);
                    var blob = new Blob([ buf ], { type: mime_type });
                    return blob;
                };
    
                window.onload = function(e) {
                    document.getElementById('preview_button').onclick = function(e) {
    
                        // open the window in the onclick handler so we don't trigger popup blocking
                        var preview_window = window.open(null, 'preview_window');
    
                        // use setTimeout to simulate an asynchronous AJAX request
                        setTimeout(function(e) {
                            var pdf_data = atob(
                                "JVBERi0xLjQKMSAwIG9iago8PCAvVHlwZSAvQ2F0YWxvZwovT3V0bGluZXMgMiAwIFIKL1BhZ2Vz" +
                                "IDMgMCBSCj4+CmVuZG9iagoyIDAgb2JqCjw8IC9UeXBlIC9PdXRsaW5lcwovQ291bnQgMAo+Pgpl" +
                                "bmRvYmoKMyAwIG9iago8PCAvVHlwZSAvUGFnZXMKL0tpZHMgWzQgMCBSXQovQ291bnQgMQo+Pgpl" +
                                "bmRvYmoKNCAwIG9iago8PCAvVHlwZSAvUGFnZQovUGFyZW50IDMgMCBSCi9NZWRpYUJveCBbMCAw" +
                                "IDUwMCAyMDBdCi9Db250ZW50cyA1IDAgUgovUmVzb3VyY2VzIDw8IC9Qcm9jU2V0IDYgMCBSCi9G" +
                                "b250IDw8IC9GMSA3IDAgUiA+Pgo+Pgo+PgplbmRvYmoKNSAwIG9iago8PCAvTGVuZ3RoIDczID4+" +
                                "CnN0cmVhbQpCVAovRjEgMjQgVGYKMTAwIDEwMCBUZAooU01BTEwgVEVTVCBQREYgRklMRSkgVGoK" +
                                "RVQKZW5kc3RyZWFtCmVuZG9iago2IDAgb2JqClsvUERGIC9UZXh0XQplbmRvYmoKNyAwIG9iago8" +
                                "PCAvVHlwZSAvRm9udAovU3VidHlwZSAvVHlwZTEKL05hbWUgL0YxCi9CYXNlRm9udCAvSGVsdmV0" +
                                "aWNhCi9FbmNvZGluZyAvTWFjUm9tYW5FbmNvZGluZwo+PgplbmRvYmoKeHJlZgowIDgKMDAwMDAw" +
                                "MDAwMCA2NTUzNSBmCjAwMDAwMDAwMDkgMDAwMDAgbgowMDAwMDAwMDc0IDAwMDAwIG4KMDAwMDAw" +
                                "MDEyMCAwMDAwMCBuCjAwMDAwMDAxNzkgMDAwMDAgbgowMDAwMDAwMzY0IDAwMDAwIG4KMDAwMDAw" +
                                "MDQ2NiAwMDAwMCBuCjAwMDAwMDA0OTYgMDAwMDAgbgp0cmFpbGVyCjw8IC9TaXplIDgKL1Jvb3Qg" +
                                "MSAwIFIKPj4Kc3RhcnR4cmVmCjYyNQolJUVPRg=="
                            );
    
                            /*
                                Warning: for my Chrome (Version 44.0.2403.155 m), the in-built PDF viewer doesn't seem 
                                to work with a blob when this html page is loaded from the local filesystem.  I have only 
                                got this to work when fetching this page via HTTP.
                            */
    
                            var pdf_blob = build_blob('application/pdf', pdf_data);
    
                            var pdf_url = window.URL.createObjectURL(pdf_blob);
    
                            preview_window.onload = function(e) {
                                console.log("preview_window.onload called");  // never happens
                                window.URL.revokeObjectURL(pdf_url);
                            };
    
                            preview_window.location.href = pdf_url;
                            console.log("preview_window.location.href set");
    
                        }, 500);
                    };
                };
            </script>
        </head>
        <body>
            <button id="preview_button">Show Preview</button>
        </body>
    </html>
    

    虽然我的上面的演示代码避免了它,但我确实为我的应用程序加载了jQuery,所以如果这样可以让事情变得更容易,我就可以使用它。

    我确实在搜索中找到了this question,但在那种情况下,主窗口(&#34;窗口&#34;)指向一个新的URL,OP在评论时从未得到回复如果窗口来自window.open,它是否会有所不同。

1 个答案:

答案 0 :(得分:0)

如您所知,您无法从开场白设置open() ed windows'onload事件。 您将不得不在第二页中注入一些将调用其window.opener函数的脚本。

但是,由于您正在打开pdf文件,浏览器将完全重新解析您的页面,您注入的代码将会消失。

正如您在评论中发现的那样,解决方案是在iframe中注入blob的url,并等待此iframe的加载事件。

以下是:

<强>的index.html

    <script>
        // The callback that our pop-up will call when loaded
        function imDone(url){
            window.URL.revokeObjectURL(url);
            }

        var build_blob = function(mime_type, data) {
            var buf = new ArrayBuffer(data.length);
            var ia = new Uint8Array(buf);
            for (var i = 0; i < data.length; i++) ia[i] = data.charCodeAt(i);
            var blob = new Blob([ buf ], { type: mime_type });
            return blob;
        };
        var preview_window=null;
        window.onload = function(e) {
            document.getElementById('preview_button').onclick = function(e) {
              if(preview_window===null || preview_window.closed){
                // open the window in the onclick handler so we don't trigger popup blocking
                preview_window = window.open('html2.html', 'preview_window');
              }
               // avoid reopening the window since it may cache our last blob
              else preview_window.focus();

                // use setTimeout to simulate an asynchronous AJAX request
                setTimeout(function(e) {
                    var pdf_data = /* Your pdf data */

                    var pdf_blob = build_blob('application/pdf', pdf_data);

                    var pdf_url = window.URL.createObjectURL(pdf_blob);
                    // Simple loop if our target document is not ready yet
                    var loopLoad = function(url){
                      var doc = preview_window.document;
                      if(doc){
                        var iframe = doc.querySelector('iframe');
                        if(iframe)iframe.src = url;
                        else setTimeout(function(){loopLoad(url);},200);
                      }
                      else setTimeout(function(){loopLoad(url);},200)
                    };
                    loopLoad(pdf_url);

                }, 0);
            };
        };
    </script>

html2.html

<html>
    <head>
        <title>Iframe PDF Demo</title>
        <style>
            body, html, iframe{margin:0; border:0}
        </style>
    </head>
    <body>
    <iframe width="100%" height="100%"></iframe>
    <script>
        document.querySelector('iframe').onload = function(){
            //first check that our src is set
            if(this.src.indexOf('blob')===0)
                // then call index.html's callback
                window.opener.imDone(this.src);
            }
    </script>
    </body>
</html>

Live Demo