I have a requirement for obtaining the content of an iframe within a web page. I found the following code which does this correctly---
<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>
Now I plan to use the above code in a Google Chrome extension- basically when I click on the button for the extension then javascript code will be injected into the web page, and here I need to obtain the content of iframe named "iframe1".
I understand that in function 'getContentFromIframe' the value of iframe's id is passed as input parameter. So I changed the code to following, hoping to obtain the content of 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
However I am not getting any value of iframe content. What I am doing wrong here? I dont know much javascript, so I suspect that my syntax is wrong somewhere?
Given below is the content of my 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"
]
}
Also given below is the error message I am getting in Javascript console, when I try to run the Google Chrome extension-
Uncaught TypeError: Cannot read property 'document' of undefined