javascript 是否可以“伪造”iframe 的 src 属性?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3462758/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 01:14:43  来源:igfitidea点击:

Is it possible to "fake" the src attribute of an iframe?

javascriptjqueryiframe

提问by Lucas

I try to add dynamically an iframe to a web page using JavaScript. I would like to know if that's possible to set the src attribute of my iframe without using another html file via an URL. I mean is there a way to "fake" the html for the src attribute file with a JS variable where we I can set my code (which is JS itself) ? I would use the DOM createElement to create the iframe in jQuery.

我尝试使用 JavaScript 将 iframe 动态添加到网页中。我想知道是否可以在不通过 URL 使用其他 html 文件的情况下设置 iframe 的 src 属性。我的意思是有没有办法“伪造”带有 JS 变量的 src 属性文件的 html,我们可以在其中设置我的代码(即 JS 本身)?我会使用 DOM createElement 在 jQuery 中创建 iframe。

Thanks !

谢谢 !

回答by Pekka

You could look into data:URIs.

您可以查看data:URIs

<iframe src="data:text/html, .... URLencoded HTML data ....">

alternatively

或者

<iframe src="data:text/html;base64, .... base64 encoded HTML data ....">

The scheme is supported by IE >= 8 (MSDN source), Firefox, Safari 3+ and Opera.

该方案被 IE >= 8 (MSDN 源)、Firefox、Safari 3+ 和 Opera 支持。

It has differing length limits. Opera is said to cut off at about 4 kilobytes; Internet Explorer at 32 kilobytes. Firefox has no explicit length limit.

它有不同的长度限制。据说 Opera 截断了大约 4 KB;32 KB 的 Internet Explorer。Firefox 没有明确的长度限制。

More on data URIs and tools for converting at Mozilla Developer Central

Mozilla 开发人员中心了解更多关于数据 URI 和转换工具的信息

回答by Ryan Brunner

If you're controlling the iframe entirely client-side, and never need to make server-side requests with that iframe, it's proably easier to style a div to appear like an iframe (look into the overflowproperty), where you'll have far simpler and more direct control to the DOM contents of that div.

如果您完全在客户端控制 iframe,并且永远不需要使用该 iframe 发出服务器端请求,那么将 div 的样式设置为看起来像 iframe(查看overflow属性)可能更容易,在那里您将有很远对该 div 的 DOM 内容进行更简单、更直接的控制。

回答by N30

following code should do what you want.

下面的代码应该做你想做的。

you can leave the src attribute empty.

您可以将 src 属性留空。

var yourcontent="<div>your stuff</div>";
window.frames['frame_name'].document.write=yourcontent;