简体   繁体   English

在另一个选项卡中重用 iframe (Javascript)

[英]Reuse iframe in another tab (Javascript)

I have this iframe in a page: document.querySelector("iframe")我在一个页面中有这个 iframe: document.querySelector("iframe")

It loads a PDF from a server.它从服务器加载 PDF。 to avoid calling another request when the user clicks on a button i want to reuse the iframe with the pdf document from this iframe: ex: <iframe src="myAPI/loadPdf.pdf"><iframe>为避免在用户单击按钮时调用另一个请求,我想将此 iframe 中的 pdf 文档重用iframe:例如: <iframe src="myAPI/loadPdf.pdf"><iframe>

When a user clicks a button:当用户单击按钮时:

var pdfWindow = window.open("");
console.log(document.querySelector("iframe"));
pdfWindow.document.write(document.querySelector("iframe"));
//to avoid making 2 request, use the one that is already loaded

This writes [object HTMLIFrameElement] on the blank page instead of the document这会在空白页而不是文档上写入[object HTMLIFrameElement]

document.write() writes a string to the document. document.write()将字符串写入文档。 You want to append the iframe node to document.body :您想将iframe节点附加到document.body

pdfWindow.document.body.appendChild(document.querySelector('iframe'))

But note that when you append the iframe you can see a request for the pdf file in the network panel, however if the browser could cache the file and the cached version is available then the cached version is used and it's not downloaded again.但请注意,当您附加 iframe 时,您可以在网络面板中看到对 pdf 文件的请求,但是如果浏览器可以缓存文件并且缓存版本可用,则使用缓存版本并且不会再次下载。 With that said it's actually no use to reuse the iframe since the same thing happens if you just open the window with the url to the pdf file, the cached version will be used if it's available.话虽如此,重用iframe实际上没有用,因为如果您只打开带有 pdf 文件的 url 的窗口,就会发生同样的事情,如果可用,将使用缓存版本。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM