Which is the difference between srcdoc=“…” and src

2019-01-31 10:50发布

For example, which is the difference between these:

<iframe srcdoc="<p>Some HTML</p>"></iframe>
<iframe src="data:text/html,<p>Some HTML</p>"></iframe>

Demo

And, in case they are exactly the same, why did HTML5 add srcdoc attribute?

Edit

Maybe I wasn't clear enough. I am not comparing src with srcdoc, but src using text/html data URI with srcdoc.

Then, if the functionality chart is like this

                   |  src attribute       |  srcdoc attribute
 --------------------------------------------------------------------
  URL              |  Yes                 |  No without using src (*)
  HTML content     |  Yes, using data URI |  Yes

why is srcdoc needed?


(*) Note:

It seems srcdoc can be used to load a page by URL (Demo), using a subiframe with srcattribute:

<iframe srcdoc="<iframe src='http://microsoft.com'></iframe>"></iframe>

标签: html iframe
8条回答
可以哭但决不认输i
2楼-- · 2019-01-31 11:24

Iframe with src attribute with HTML Content is cross domain,

But iframe with srcDoc attribute with HTML Content is not cross domain

查看更多
劳资没心,怎么记你
3楼-- · 2019-01-31 11:27

The other answers list some superficial differences, but really miss the mark of the key difference that explains why browsers/spec writers would essentially duplicate something that already exists:

<iframe src="data:...untrusted content" sandbox /> <- Secure in modern browsers, insecure in legacy browsers with no sandbox support

<iframe srcdoc="...untrusted content" sandbox /> <- Secure in modern browsers, secure (though non-functional) in legacy browsers

This new syntax provides content authors a way to protect their users, even when they may be using legacy browsers. Without it, content authors would be reluctant to use the sandbox feature at all, and it would not see use.

查看更多
登录 后发表回答