append meta tag to the head of the main document f

2019-07-19 04:20发布

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>

2条回答
叼着烟拽天下
2楼-- · 2019-07-19 04:29

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);
查看更多
走好不送
3楼-- · 2019-07-19 04:44

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);
查看更多
登录 后发表回答