Is it possible to add Request Headers to an iframe src request?

后端 未结 4 1607
栀梦
栀梦 2020-12-02 09:52

I understand that you can set HTTP request headers very easily when making AJAX calls in JavaScript.

However is it also possible to set custom HTTP request headers w

4条回答
  •  难免孤独
    2020-12-02 10:11

    It turns out that URL.createObjectURL() is deprecated in Chrome 71
    (see https://developers.google.com/web/updates/2018/10/chrome-71-deps-rems)
    Building on @Niet the dark Absol and @FellowMD's excellent answers, here's how to load a file into an iframe, if you need to pass in authentication headers. (You can't just set the src attribute to the URL):

    $scope.load() {
        var iframe = #angular.element("#reportViewer");
        var url = "http://your.url.com/path/etc";
        var token = "your-long-auth-token";
        var headers = [['Authorization', 'Bearer ' + token]];
        $scope.populateIframe(iframe, url, headers);
    }
    
    $scope.populateIframe = function (iframe, url, headers) {
        var xhr = new XMLHttpRequest();
        xhr.open('GET', url);
        xhr.onreadystatechange = handler;
        xhr.responseType = 'document';
        headers.forEach(function (header) {
            xhr.setRequestHeader(header[0], header[1]);
        });
        xhr.send();
    
        function handler() {
            if (this.readyState === this.DONE) {
                if (this.status === 200) {
                    var content = iframe[0].contentWindow ||
                        iframe[0].contentDocument.document || 
                        iframe[0].contentDocument;
                    content.document.open();
                    content.document.write(this.response.documentElement.innerHTML);
                    content.document.close();
                } else {
                    iframe.attr('srcdoc', 'Error loading page.');
                }
            }
        }
    }
    

    and shoutout to courajs: https://github.com/courajs/pdf-poc/blob/master/script.js

提交回复
热议问题