乐闻世界logo
搜索文章和话题

Is it possible to add request headers to an iframe src request

4个答案

1
2
3
4

No, the src attribute of an iframe does not allow adding request headers directly. When an iframe loads a resource, the browser sends a default GET request and cannot specify request headers directly within the src attribute.

However, there are methods to achieve similar effects, though they do not involve adding request headers directly in the iframe's src attribute.

  1. Server-Side Configuration: You can pre-configure request headers on the server. When the iframe requests the resource, the server sends these pre-configured headers. The limitation is that it cannot dynamically adjust the request headers based on client requirements.

  2. Using JavaScript and CORS: If you control the server hosting the page loaded by the iframe, you can use fetch or XMLHttpRequest to send requests with custom headers and dynamically insert the content into an iframe or other DOM elements after receiving the response. This requires the server to support Cross-Origin Resource Sharing (CORS) to allow such requests.

Example:

javascript
fetch('https://example.com/page', { method: 'GET', headers: { 'Custom-Header': 'value' } }) .then(response => response.text()) .then(html => { const iframe = document.createElement('iframe'); document.body.appendChild(iframe); iframe.contentWindow.document.open(); iframe.contentWindow.document.write(html); iframe.contentWindow.document.close(); }) .catch(error => console.error(error));
  1. Using a Server-Side Proxy: You can create a server-side proxy that adds the required request headers. The iframe can then point to this proxy. The proxy handles requests from the iframe, adds the headers, forwards the request to the final destination, and processes the response to return it to the iframe.

In summary, while you cannot directly add request headers to the iframe's src attribute, you can achieve similar effects using server-side logic or client-side scripts in a programmatic way. These methods have their own trade-offs and are suitable for different scenarios.

2024年6月29日 12:07 回复

It turns out that URL.createObjectURL() has been deprecated in Chrome 71 (see [https://developers.google.com/web/updates/2018/10/chrome-71-deps-rems]). Based on the excellent answers from @Niet Dark Absol and @FellowMD, if you need to pass authentication headers, here's how to load a file into an iframe. (You cannot simply set the src attribute to a URL):

javascript
$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', '<html><head></head><body>Error loading page.</body></html>'); } } } }

And a tribute to courajs: [https://github.com/courajs/pdf-poc/blob/master/script.js]

2024年6月29日 12:07 回复

Due to the deprecation of createObjectURL, @FellowMD's answer is no longer applicable to modern browsers, so I adopted a similar approach but using the iframe srcdoc attribute.

  1. Retrieve the content to be displayed in the iframe using XMLHttpRequest or any other method.

  2. Set the srcdoc parameter of the iframe.

Here is a React example (I know this is somewhat excessive):

javascript
import React, {useEffect, useState} from 'react'; function App() { const [content, setContent] = useState(''); useEffect(() => { // Fetch the content using the method of your choice const fetchedContent = '<h1>Some HTML</h1>'; setContent(fetchedContent); }, []); return ( <div className="App"> <iframe sandbox id="inlineFrameExample" title="Inline Frame Example" width="300" height="200" srcDoc={content}> </iframe> </div> ); } export default App;

Most modern browsers now support srcdoc. It appears Edge implemented it slightly later: https://caniuse.com/#feat=iframe-srcdoc

2024年6月29日 12:07 回复

You can make requests in JavaScript and set any headers you want. Then you can use URL.createObjectURL() to obtain a URL suitable for the src attribute of an iframe.

javascript
var xhr = new XMLHttpRequest(); xhr.open('GET', 'page.html'); xhr.onreadystatechange = handler; xhr.responseType = 'blob'; xhr.setRequestHeader('Authorization', 'Bearer ' + token); xhr.send(); function handler() { if (this.readyState === this.DONE) { if (this.status === 200) { // this.response is a Blob, because we set responseType above var data_url = URL.createObjectURL(this.response); document.querySelector('#output-frame-id').src = data_url; } else { console.error('no pdf :('); } } }

Preserve the MIME type of the response. Therefore, if you receive an HTML response, it will be displayed in the iframe. If you request a PDF, the browser's PDF viewer will launch within the iframe.

If this is part of a long-running client application, you may need to use URL.revokeObjectURL() to prevent memory leaks.

Object URLs are also interesting. They take the form blob:https://your.domain/1e8def13-3817-4eab-ad8a-160923995170. You can actually open them in a new tab to view the response, and they will be discarded when the context that created them is closed.

Here is a complete example: https://github.com/courajs/pdf-poc

2024年6月29日 12:07 回复

你的答案