Is there a way to add a custom http header into the request done by an <iframe>
when changing the source (src) using javascript?
相关问题
- Is there a limit to how many levels you can nest i
- How to toggle on Order in ReactJS
- void before promise syntax
- Keeping track of variable instances
- Can php detect if javascript is on or not?
The following code works. It is a modification of the code provided by Matthew Graves, modified to use the
srcdoc
attribute to solve the problem of CSS and JavaScript references not been ran. Unfortunately, it is only working in Chrome.Edit: Finally, I have resolved the issue of the scripts blocks cross-browser, by reassigning them to the iframe on document.ready function:
Rather than using a data URI, or setting the contents to a string, you can use
URL.createObjectURL()
, and set it as thesrc
of the iframe.The object URLs are pretty interesting. They're of the form
blob:https://your.domain/1e8def13-3817-4eab-ad8a-160923995170
. You can actually open them in a new tab and see the response, and they're discarded when the context that created them is closed.Here's a full example: https://github.com/courajs/pdf-poc
You can have the results of an ajax request that has custom headers be set as the content of an iframe like so:
This is assuming the iframe is pointing at a cross domain src. It is simpler if everything is on the same domain.
Edit: Maybe try this variation.
I ended up going with the approach proposed by the other answers here, that use ajax to get the html string and then directly set the contents of the
iFrame
.However, I used the approach posted in this answer to actually set the contents of the
iFrame
, as I found it worked well cross platform with almost all devices I could dig up.Tested - successful:
^ confirmed that linked css and js in the content run correctly (others not tested)
Tested - unsuccessful:
So putting them together gives something like this (Note: I havn't actually run this exact code):
Here's an example of setting the
iFrame
contents in this JS BinEdit: Here's the html part
Edit 2:
The solution above appears to no longer be working in Firefox (50.1.0) for some unknown reason. Using the solution in this answer I've now changed to code to the example below, which also seems to be more robust: