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

后端 未结 4 1600
栀梦
栀梦 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:02

    As @FellowMD answer is not working on modern browsers due to the depreciation of createObjectURL, I used the same approach but using iframe srcDoc attribute.

    1. Retrieve the content to display in the iframe using XMLHttpRequest or any other method
    2. Set the srcdoc parameter of the iframe

    Please find below a React example (I know it is overkill):

    import React, {useEffect, useState} from 'react';
    
    function App() {
      const [content, setContent] = useState('');
    
    
      useEffect(() => {
        // Fetch the content using the method of your choice
        const fetchedContent = '

    Some HTML

    '; setContent(fetchedContent); }, []); return (
    ); } export default App;

    Srcdoc is now supported on most browsers. It seems that Edge was a bit late to implement it: https://caniuse.com/#feat=iframe-srcdoc

提交回复
热议问题