How to close window after iframe form submits - javascript

I have a blank page with an iframe that displays a form from an external domain outside my control. I'm trying to write a bit of Javascript/jQuery that will close the window after the form is submitted.
Here's my code:
<body>
<script>
$('iframe input[type="submit"]').on('click', function () {
window.close();
});
</script>
<iframe src="SomeOtherDomain.com"></iframe>
</body>
Nothing happens when I click the button though. What am I doing wrong?
EDIT:
I'm not sure if it makes a difference or not but it looks like the iframe calls a second iframe... I've got an iframe inside an iframe.

I believe you need to provide some time(100 ms) to submit the form data. Please try this by calling the deleteIframeTimer
function deleteIframeTimer(){
var t = setTimeout("deleteIframe()", 100);
}
function deleteIframe() {
var iframe = parent.document.getElementById("myframe");
iframe.parentNode.removeChild(iframe);
}

So long as your iframe src is from the same domain this will work:
$(document).ready(function () {
var f = $('#myframe')[0];
var win = f.contentWindow;
//Created test environment in IFrame with ID "myframe"
$(win.document.body).append('<form><input type="submit" value="click me"/></form>');
$(win.document).on('submit', function () {
setTimeout(function () { $(f).remove(); }, 1000)
});
});
Simply remove the element but remember you can't get the contentDocument from an iframe that is not of the same domain.
Working solution:
https://jsfiddle.net/f3eayurw/

Related

Get the class of an element clicked upon in an iframe?

How can I get the class of an element clicked upon in an iframe?
HTML:
<input id="tag" type="text">
<iframe id="framer" src="SameDomainSamePort.html"></iframe>
JS:
$(document).ready(function () {
$("iframe").each(function () {
//Using closures to capture each one
var iframe = $(this);
iframe.on("load", function () { //Make sure it is fully loaded
iframe.contents().click(function (event) {
iframe.trigger("click");
});
});
iframe.bind("click", function(e) {
// always returns the iframe rather than the element selected within the iframe...
$("#tag", window.top.document).val($(e)[0].target.className);
return false;
});
});
});
Would it be easier to inject js?
And could I add css as well?
All help is appreciated!
Here should be enough tools to do what you want
Also the load event cannot be used unless you set the src later, because it has already triggered when you run your code
The fiddle works: https://jsfiddle.net/mplungjan/kqeqzusf/
SO have more stringent sandbox issues but also look at
SecurityError: Blocked a frame with origin from accessing a cross-origin frame
$(function() {
$(".iframe").each(function(i) {
var doc = $(this)[0].contentWindow.document;
var $body = $('body',doc);
$body.html(`<div id="test${i}">Click me ${i}</div>`); // or set the source
$body.on("click",function(e) { // assign a handler
console.log(e.target.id);
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<div id="container">
<iframe id="iframe1" class="iframe"></iframe>
<iframe id="iframe2" class="iframe"></iframe>
</div>
More:
putting html inside an iframe (using javascript)
jQuery/JavaScript: accessing contents of an iframe
jQuery/JavaScript: accessing contents of an iframe
[jQuery]Find click inside an iFrame

Onload event does not trigger

I want to send some data via postMessage from a page to another one which have different domains. However, I cannot achieve that since the code inside $(yo.document).load never runs; I tried the commented version as well. Here is my code:
<a onclick="popupCenter('http://localhost:58810');" href="javascript:void(0);">CLICK</a>
<script>
function popupCenter(url) {
const yo = window.open(url);
$(yo.document).load(function() {
//yo.document.onload = function() {
console.log("yo loaded");
yo.postMessage("Hello mate", "*");
});
}
</script>
</body>
</html>
The new window opens normally, however the callback inside load is not called. Any ideas?

Remove id from iframe

I have an iframe of a certain page from a site that I'm using, but I don't want all the parts of that page to be displayed with the iframe. Particularly, there's a navigation sidebar on the page that I don't want to be in the iframe. I'm trying to achieve this with the javascript seen below, but I can't quite figure it out.
<iframe width="800" height="800" src="scores/new?site_id=193">
<script>
var element = document.getElementById("sidebar-wrapper");
element.parentNode.removeChild(element);
</script>
</iframe>
For security reasons you can't run javascript through iframes. There are some exceptions if you're on the same domain but for the most part you should really avoid it.
If the iframe isn't a site you can control then there's pretty much nothing you can do. If you do control the other site and it's a different domain you might be able to work with the postMessage functions.
Edit: Check out the docs that Mozilla has up here https://developer.mozilla.org/en-US/docs/Web/API/Window/postMessage
You'd need to create a listener on the inside that handles a message and hides your sidebar. Then on the parent send a message to the iframe to trigger that function.
Parent:
var iframe = document.getElementById('#iframeID');
iframe.contentWindow.postMessage('iframeTrigger');
Iframe:
window.addEventListener('iframeTrigger', hideSidebar);
function hideSidebar() {
//do stuff
}
You can insert a control in the iframed page
//inside the iframed page
var iframe = (function() {
try {
return window.self !== window.top;
} catch (e) {
return true;
}
})();
if(iframe === true) {
var element = document.getElementById("sidebar-wrapper");
element.parentNode.removeChild(element);
}
Hope this could suit your need.
This should work theoretically, and it works in console. But this doesn't work in the HTML, although you are trying it from the same domain, because of security reasons. I just wanted to tell my view and I tried this:
<iframe src="http://output.jsbin.com/figujeyiyo" frameborder="0" id="ifrm">
Sorry, iframes not supported.
</iframe>
<script>
console.log(document.getElementById("ifrm").contentDocument.documentElement.getElementsByTagName("div"));
e = document.getElementById("ifrm").contentDocument.documentElement.getElementsByTagName("div")[0];
console.log(e);
e.parentNode.removeChild(element);
</script>
You need to execute the code when the page loads, you can do it like this:
document.addEventListener('DOMContentLoaded', function() {
var element = document.getElementById("sidebar-wrapper");
element.parentNode.removeChild(element);
});

JavaScript not being inputted into iframe

I have a textarea box where the user inputs HTML and it gets output into the body element of an iframe.
This works just fine using most HTML tags, but if you use the <script> tag (in order to add JavaScript), the script element does not get transferred to the iframe.
For example, I should be able type the following in the textarea:
<script>
function test() {
alert('test');
}
</script>
<button onclick="test()">test</button>
The button gets added to the iframe but since the script element apparently doesn't, clicking the button does not fire the alert().
One work-around for this is to declare alert() on the button click, rather than using a pre-scripted function; this work-around is shown below:
<button onclick="alert('test')">test</button>
However this only allows one javascript command (whereas the user may want to use a function with multiple commands).
You can see the webpage here
The JavaScript to fill the iframe contents is:
(function () {
$('.grid').height($(window).height());
var frame = $('iframe'),
contents = frame.contents(),
body = contents.find('body'),
styleTag = contents.find('head')
.append('<style></style>')
.children('style');
$('textarea').focus(function () {
var $this = $(this);
$this.keyup(function () {
if ($this.attr('id') === 'html') {
body.html($this.val());
} else {
styleTag.text($this.val());
}
});
});
})();
The problem is any "user-generated" scripts will be executed in the parent window's global context (which the iframe cannot [normally] access). The console shows the following error when clicking the button because the test() function is not accessible scope-wise for the iframe:
Uncaught ReferenceError: test is not defined
To fix this, scripts need to add functions to the global scope of the iframe's internal window:
<script>
(function () {
'use strict';
var iframe = document.getElementById('iframe'), //grab the iframe
win = iframe.contentWindow; //get the window of the iframe
win.test = function () { //declare function in scope of iframe's window
alert('test'); //now "test" will fire because it's defined in a scope accessible to the iframe
};
}());
</script>
<button onclick="test()">test</button>

Remove current iframe

I have an HTML page that opens an IFRAME ... But at some point, after some user interactions with the IFRAME, it should close itself. I've tried various commands such as:
var fram = $("IFRAME_NAME");
fram.parentNode.removeChild(fram);
this.remove();
this.style.display='none';
var frame = parent.frames['IFRAME_NAME'];
frame.remove();
frame.html("");
document.IFRAME_NAME.document.body.innerHTML = '';
Thanks.
Considering markup like this:
<iframe id="myframe" />
The following jQuery code will remove it in the host page:
$("#myframe").remove();
To close the iframe from within iframe itself, define the function in the host page:
function closeFrame() {
$("#myframe").remove();
}
Then in the code running in the iframe, call:
parent.closeFrame();
If you are using jQuery (and I've understood your question properly), you can use a code as simple as:
<iframe src="http://www.google.com" id="testframe"></iframe>
<script>
$(document).ready(function() {
setTimeout(function () {
$('#testframe').remove();
},5000);
});
</script>
http://jsfiddle.net/pYHx5/

Categories

Resources