append meta tag to the head of the main document from iframe

*爱你&永不变心* 提交于 2019-12-11 02:12:33

问题


So I've got an issue where i've made a document responsive but it's displayed in an iframe which where the parent document has the wrong meta tag.

I set up a test to see if i could do it in an iframe. It's appending the meta tag to the head of the iframe not the main document. Anyone have any suggestions?

index.html

<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title>Iframe Test</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">

</head>
<body>

<iframe id="testFrame" name="testFrame" src="iframe.html"></iframe>

</body>
</html>

iframe.html

<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title>Iframe</title>

<script>
var viewPortTag=document.createElement('meta');
viewPortTag.id="viewport";
viewPortTag.name = "viewport";
viewPortTag.content = "width=device-width; initial-scale=1.0; maximum-scale=1.0; user-scalable=0;";
document.getElementsByTagName('head')[0].appendChild(viewPortTag);

</script>
</head>
<body>
Iframe Original Content
</body>
</html>

回答1:


You can do it, but only if the domain of the iframe is the same of the top document's domain.

Just change your code to:

window.parent.document.getElementsByTagName('head')[0].appendChild(viewPortTag);



回答2:


Use window.parent.document instead of document in iframe.html. Assuming both files are on the same domain.

var viewPortTag=document.createElement('meta');
viewPortTag.id="viewport";
viewPortTag.name = "viewport";
viewPortTag.content = "width=device-width; initial-scale=1.0; maximum-scale=1.0; user-scalable=0;";
window.parent.document.getElementsByTagName('head')[0].appendChild(viewPortTag);


来源:https://stackoverflow.com/questions/18113507/append-meta-tag-to-the-head-of-the-main-document-from-iframe

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!