Export current iframe content as HTML file - javascript

Here is the thing - I'm trying to create kind of email signature generator. Most of the index file, is a pure HTML code + tiny javascript. Inside index file I'm embeding email signature template as an iframe/email_signature.html file. So it looks as follows:
<iframe src="email_signature.html" width="100%" height="350" frameborder="0" id="testing" name="emailSignature"></iframe>
Then I'm trying to download current content of this iframe by executing this code:
$(document).ready(function() {
const innerFrame = document.getElementById('testing').contentWindow.document.body.innerHTML;
$("#cmd").click(function(){
exportFile('new-file.html', $innerFrame.innerHTML);
});
});
but it doesn't work. Here is the example fiddle:
https://jsfiddle.net/py1tojmc/
What I'm doing wrong here?

From what I can see in the dev console opening your jsfiddle, i don't see any "event" attached to your download button.
I can't tell you why this is happening (I'm not that expert), but maybe the call to .contentWindow.document.body.innerHTML; is somehow changing the DOM context to the iframe (just a guess), and it seems you cannot access the button id #cmd anymore.
Try changing your code like this ans see if it works:
$(document).ready(function() {
$("#cmd").click(function(){
const innerFrame = document.getElementById('testing').contentWindow.document.body.innerHTML;
exportFile('new-file.html', $innerFrame.innerHTML);
});
});

Yeah looks like the button event won't fire. But could be cross origin security:
SecurityError: Permission denied to access property "document" on cross-origin object
But that could just be the jsfiddle, can you put an alert('cmd button works'); just to make sure your button fires?

Related

Access CURRENT src in embed object HTML

I have created an embed object in HTML and this code in Javascript:
function mainLoop() {
var browser = document.getElementById("browser");
console.log(browser.src);
}
//call main loop
setInterval(mainLoop, 1000);
<embed src="https://en.wikipedia.org/wiki/Main_Page" id=browser>
When I run the webpage, the console constantly prints "https://en.wikipedia.org/wiki/Main_Page", which is what is expected. However, when I click on a link inside the embed HTML to change the webpage inside the embed HTML, the console continues to print "https://en.wikipedia.org/wiki/Main_Page".
How do I access the current URL of the content inside of the embed HTML?
(I cannot use browser.contentWindow because of a Security Error)
Unfortunately due to CORS, this is impossible. Perhaps find a different way of doing this, or make a page similar to the one shown.
You cannot access the src of an iframe that is from another domain.

Cross domain postMessage, identify iFrame

I use postMessage to send events from an iframe to it's parent document. I have control over both sides but the content comes from two different domains.
My simple problem is, that i can not identify the iFrame inside of it's parent callback method. The implementation looks like this:
In the iFrame:
parent.postMessage(JSON.stringify({action: "closeView" }),'*');
In the parent window:
window.addEventListener('message',function(event) {
if(event.origin !== 'https://example.com')
return;
// Parse message back to json
var messageObject = JSON.parse(event.data);
var source = event.source;
/* this is returning: Window -URL- */
console.log( source );
/* This will throw Permission denied, although this code is inside of "parent" */
console.log(source.parentNode);
},false);
I want to identify a certain parent element of the iframe, which is (logically) inside of the parent document.
When i try to use event.source.parentNode or some jQuery on said object, Firefox says, i can not do this to prevent XSS, error: Error: Permission denied to access property 'parentNode'
How can i get the parent element of the iFrame, that triggered the postMessage event listener?
you can use window names for this, as they pass from iframe tag to iframe context.
parent doc:
<iframe name=fr2 src="data:text/html,%3Chtml%3E%0A%20%3Cscript%3E%20parent.postMessage%28%7Bname%3A%20window.name%7D%2C%20%22*%22%29%3B%3C/script%3E%0A%3C/html%3E"></iframe>
<iframe name=fr3 src="data:text/html,%3Chtml%3E%0A%20%3Cscript%3E%20parent.postMessage%28%7Bname%3A%20name%7D%2C%20%22*%22%29%3B%3C/script%3E%0A%3C/html%3E"></iframe>
<script>onmessage = function(e){ // use real event handlers in production
alert("from frame: " + e.data.name);
};</script>
iframe doc:
<html>
<script> parent.postMessage({name: name}, "*");</script>
</html>
which alerts "fr2", then "fr3".
you can then easily use the name attrib to find the iframe in the parent DOM using attrib CSS selectors.
illustrative demo of window.name+iframe concept: http://pagedemos.com/namingframes/
this painfully simple approach is also immune to issues arising from same-url iframes.
As per my understanding this may be try
here suppose your main window's url is www.abc.com\home.php
<body>
<iframe src="www.abc.com\getOtherDomainContent.php?otherUrl=www.xyz.com"/>
</body>
getOtherDomainContent.php in this file need to write ajax call which get cross url content and push that content in current iframe window(getOtherDomainContent.php)'s body part.
getOtherDomainContent.php
Code:
<html>
<head>
//import jqry lib or other you use.
<script>
$(document).ready({
//getcontent of xyz.com
var otherUrlContent=getAjaxHtml("www.xyz.com");
$("body").html(otherUrlContent);
// further code after content pushed.
//you can easily access "parent.document" and else using parent which will give you all thing you want to do with your main window
});
</script>
</head>
</html>
Like seen in this thread: postMessage Source IFrame it is possible to compare each iframes contentWindow with event.source like this:
/*each(iframe...){ */
frames[i].contentWindow === event.source
But i did not like this too much. My solution for now looks like this:
In the iFrame:
parent.postMessage(JSON.stringify({action: "closeView", viewUrl: document.URL}),'*');
Update:
docuent.URL can become a problem, when you use queries or links with location (#anchor) since your current url will become different from the one of the iframe source. So Instead of document.URL it's better to use [location.protocol, '//', location.host, location.pathname].join('') (Is there any method to get the URL without query string?)
In the parent document:
window.addEventListener('message',function(event) {
if(event.origin !== 'https://example.com')
return;
// Parse message back to json
var messageObject = JSON.parse(event.data);
// Get event triggering iFrame
var triggerFrame = $('iframe[src="'+messageObject.viewUrl+'"]');
},false);
Each event will have to send the current iFrame URL to the parent document. We now can scan our documents for the iFrame with the given URL and work with it.
If some of you know a better way please post your answers.

JavaScript doesn't change iframe src (using Bootstrap frontend)

I am using the following JavaScript (in the script tag in head) to modify an iframe's src when a link is clicked.
function switchView() {
document.getElementById("project-view").src = 'projects/3dpool.html';
}
My iframe is written as
<iframe id="project-view" src="projects/fallingballs.html" onload="resizeIframe(this);" scrolling="no"></iframe>
The link that changes the iframe is:
3D Pool
Adding a log statement like document.getElementById("project-view").src after the src change shows that the src has actually changed but no changes show up.
I have tried removing the unload tag from the iframe but it doesn't help.
Typing out the code in the switchView() function in the web console works
Change your link to look like the following:
3D Pool

JavaScript to get some information from inside the HTML at an arbitrary URL?

Sorry, I'm don't know the right terminology to look this up by keyword...
So, as a simple newbie exercise, I tried to make a file "test.html" (just on my desktop) such that when I load it my browser and click the button that appears on the page, the article count from Wikipedia's main page will appear on the page under the button.
Somebody told me to try using an iframe, and I came up with this:
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript"">
function get_count(){
var articlecount = document.getElementById("wiki_page").contentWindow.document.getElementById("articlecount").getElementsByTagName("a")[0].innerHTML;
document.getElementById("put_number_here").innerHTML = articlecount;
}
</script>
</head>
<body>
<iframe id="wiki_page" style="display:none" src="http://en.wikipedia.org/wiki/Main_Page"></iframe>
<input type="button" onclick="get_count()" />
<p id="put_number_here"><p>
</body>
</html>
It doesn't work, and when I test this in the scratchpad (using Firefox 17), I get this:
var x = document.getElementById("wiki_page").contentWindow.document.getElementById("articlecount").getElementsByTagName("a")[0].innerHTML;
alert(x);
/*
Exception: Permission denied to access property 'document'
#Scratchpad:10
*/
(And alert(document.getElementById("articlecount").getElementsByTagName("a")[0].innerHTML); works perfectly on http://en.wikipedia.org/wiki/Main_Page directly, so I know that's not the problem. Copying the source of the wikipedia main page to a new file "test2.html", and setting that as the src of the iframe, that also works.)
Am I just trying to do this in completely the wrong way?
You cannot access any elements inside an iFrame unless, the iFrame is referring the same domain.
for same domain calls, use this link for reference :
Calling a parent window function from an iframe
for different domain, user this link for reference :
How do I implement Cross Domain URL Access from an Iframe using Javascript? script
You can reference the other frame by using:
window.frames["wiki_page"]
Then you can reference the element in the DOM by using:
window.frames["wiki_page"].document.getElementById ("articlecount");
So in your case you could try:
var targetFrame = window.frames["wiki_page"];
Then Access the elements using:
targetFrame.document.getElementById("IDOfSomething");
Make sure your iframe is still named wiki_page etc...

How to resize an IFRAME on load in an .aspx page?

In an .aspx page with a VB.NET codebehind I am using an IFRAME which would be created inside the repeater control.
Since I want to resize the IFRAME based on the content within the page I have been using the resize function obtained from here on the IFRAME onload as shown below.
<iframe id="IframeSubsectionArea" scrolling="auto" width="100%" onload="resizeIframeToFitContent(this)" runat="server">
However it is throwing an error as the method could not be found in the form.
Is there any client side script variant for the onload event?
What might be the reason for the error and its solution?
If you don't mind using jQuery the first answer on here should do the trick
jQuery .ready in a dynamically inserted iframe
$(document).ready(function() {
$("iframe").load(function() {
var iframe = $(this);
//Do your resize here via the iframe var
});
});
Failing that, you may be getting the error due to this block of code being missing from your document however as you have not posted the actual error i cannot be sure.
<SCRIPT LANGUAGE="JavaScript">
function resizeIframeToFitContent(iframe) {
// This function resizes an IFrame object
// to fit its content.
// The IFrame tag must have a unique ID attribute.
iframe.height = document.frames[iframe.id]
.document.body.scrollHeight;
}
</SCRIPT>
Edit: If that doesn't work post some example code, and the actual error you are getting

Categories