我需要在网页中获取iframe的内容。我发现以下代码可以正确地执行此操作---
<html>
<head>
</head>
<body>
<script type="text/javascript"> <!-- Function can also be loaded from an external file -->
function getContentFromIframe(iFrameName) // the function has one parameter: the iframe's ID.
{ // I did it this way, so you can call it for multiple iframes.
var myIFrame = document.getElementById(iFrameName); // Creating an object of the iframe
var content = myIFrame.contentWindow.document.body.innerHTML; // Getting it's content into a variable
// Basically now, in the variable 'content' you have the content of your iframe,
// and can do anything you want with it.
alert('content: ' + content); // here it is
// You can even choose to change it afterwards
content = 'The inside of my frame has now changed'; // create a new content
myIFrame.contentWindow.document.body.innerHTML = content; // and set it
}
</script>
<iframe id="iframe1" src="http://www.google.com/"></iframe> <!-- Instantiating the iframe -->
<br />
<a href="#" onclick="getContentFromIframe('iframe1')">Get the content</a> <!-- Calling the function -->
</body>
</html>
现在我计划在Google Chrome扩展程序中使用上述代码 - 基本上当我点击扩展按钮时,javascript代码将被注入网页,在这里我需要获取名为“iframe”的内容iframe1" 。
据我所知,在函数'getContentFromIframe'中,iframe id的值作为输入参数传递。所以我将代码更改为以下内容,希望获得iframe的内容 -
var myIFrame = document.getElementById('iframe1'); // Creating an object of the iframe
var content = myIFrame.contentWindow.document.body.innerHTML; // Getting it's content into a variable
// Basically now, in the variable 'content' you have the content of your iframe,
// and can do anything you want with it.
alert('content: ' + content); // here it is
但是我没有获得任何iframe内容的价值。我在这做错了什么?我不太了解javascript,所以我怀疑我的语法在某处错了?
以下是我的manifest.json ---
的内容{
"name": "Link Submitter",
"version": "1.0",
"background_page": "bg.html",
"description": "Link Submitter by SEO Power Toys",
"browser_action": {
"name": "Send Data",
"default_icon": "icon.png",
"default_title": "Send data to Link Submitter" // optional; shown in tooltip
},
"permissions": [ "tabs",
"bookmarks",
"http://*/*",
"https://*/*",
"unlimitedStorage"
]
}
以下是我尝试运行Google Chrome扩展程序时在Javascript控制台中收到的错误消息 -
Uncaught TypeError: Cannot read property 'document' of undefined
答案 0 :(得分:1)
您无法直接访问或操纵包含来自与您自己的域不同的域的内容的<iframe>
元素的内容。帧之间有一些通信方式,但它们需要准备两个域的内容来做到这一点;你不能指望任何随机页面与那些(相当新的)API一起使用。
现在,从扩展,当然,规则是不同的。但是,如果您正在使用常规网页上的代码,它将无法正常工作。
编辑 - Here是您的代码的测试用例。它似乎工作得很好。