js iframe close button - javascript

I Have the following which opens an iframe with html page loaded, works great, but how to add a close button to the page/iframe so it simply closes the iframe/page and does not affect the page its opened over:
(function (d) {
var modal = document.createElement('iframe');
modal.setAttribute('src', 'mypage.html'));
modal.setAttribute('scrolling', 'no');
modal.className = 'modal';document.body.appendChild(modal);
var c = document.createElement('link');
c.type = 'text/css';
c.rel = 'stylesheet';
c.href = '//myurl.com/testes.css';
document.body.appendChild(c);
}(document));
I tried the following which tried to close it, but, then gives a 404 message inside the iframe:
Close
I am loading jquery on the page if that helps at all, meaning, if there is a jquery solution.

Links are supposed to link somewhere and the href attribute takes a URI.
Use a <button type="button"> and bind a click handler to it. (You could use an onclick attribute, but that wouldn't be unobtrusive)
The unobtrusive approach would be:
foo
And then bind an event handler along the lines of
myLink.addEventListener('click', function (e) {
var d = window.parent.document;
var frame = d.getElementById('myFrame');
frame.parentNode.removeChild(frame);
e.preventDefault();
});

You could put the link into some kind of container div for your iframe, creating the latter with this structure:
<div id="iframe-container">
<a href='#' onclick='this.parentNode.parentNode.removeChild(this.parentNode)'>Close</a>
<iframe src="http://some.web/page.html" />
</div>
Works without any framework.

Related

adding 'target' attribute to an element with pure javascript

I am trying to add an target="_blank" attribute to an <a> element in my javascript but it's seems like my function disturb the element in some way and won't add it.
note without the function the target="_blank" working fine, only when I add the animation and delay function it's disabling it.
HTML and JS:
var fbId = document.getElementById('fb-id');
fbId.addEventListener('click', function(e) {
fbId.classList.add("animated", "bounceOut");
fbId.setAttribute('target', '_blank');
e.preventDefault();
var fbLink = fbId.href;
setTimeout(function(url) {
window.location = url;
}, 1000, fbLink);
});
<div class="col-3">
<a id="fb-id" href="https://www.facebook.com" target="_blank">
<img class="social-icon" id="fb-icon" src="img/fb.png" alt="facebook">
</a>
</div>
you're using the wrong function - you need to use:
window.open("http://www.google.at", '_blank');
Full Code:
var fbId = document.getElementById('fb-id');
fbId.addEventListener('click', function(e){
fbId.classList.add("animated", "bounceOut");
e.preventDefault();
var fbLink = fbId.href;
setTimeout(function(url) { window.open(url, '_blank'); }, 1000, fbLink);
});
See the working JsFiddle: http://jsfiddle.net/c29u4w7o/43/ which adapts your code so that the window will be opened in a new tab.
Your delay does not delay following the link.
You completely cancel the behaviour of following the link, and then assign a new value to location.
The target attribute is successfully added, but it doesn't get used because the link isn't followed (the browser is navigated via the location assignment instead).
If you want to navigate in a new window using JavaScript, then call window.open() instead of assigning to location.

How do I execute javascript only relative to that frame and not the whole window?

I have the following iFrame:
<div id="sandbox-inner">
<iframe sandbox="allow-forms allow-pointer-lock allow-popups allow-same-origin allow-scripts" frameborder="0" name="Output " id="output" src="JavaScript:''"></iframe>
</div>
And when the user clicks to run their code, it injects the javascript successfully within this iframe. However, it actually runs it across the whole window, not just the iframe. So basically if I add a class "test" to an element outside the iframe, and one inside, and then inject the following inside the head of the iframe...
$(function() {
$('.test').css({ background: "blue" });
});
It effects my element outside the iframe too, which I really dont want. I need the iFrame to be a completely seperate environment. This is how I am currently injecting the javascript:
$('#runGuestCode').on("click", function () {
var js = $('#js-input').val(),
iframe = $("#output"),
iframeHead = iframe.contents().find("head").first(),
frame = document.getElementById("output"),
scriptTag = '<script>' + js + '<\/script>';
$('#output').contents().find("head").append(scriptTag);
});
Many thanks
UPDATE #1
The javascript is taken from textarea #js-input, which is whatever the user has typed. This is then appended to the head of the iframe, but currently runs relative to the parent document, not the iframe document.
You can do it following way, it will not effect you current page elements will apply to iframe element only:-
var iframe = $('iframe');
$(element, iframe.contents()).css({'background':'blue'});
Working Fiddle
Showcase the javascript code put by user in iframe:
$('#submit1').click(function (e) {
e.preventDefault();
var myIframe = document.getElementById("resultFrame");
var s = document.createElement("script");
s.type = "text/javascript";
s.innerHTML = $("#textarea1").val();
myIframe.contentWindow.document.head.appendChild(s);
});
Working Fiddle with Javascript Output in iframe

jquery iframe a links into new div / tab / window?

I have a tricky question.
All pages are within same server / portal.
I have a page that embeds iframe from the other page using the following code:
$('#mydiv').append('<p id="loading">Loading ...</p>');
$('#mydiv').append('<iframe id="myframe" name="myframe" class="myframe" onload="myframe()" style="display:none;"></iframe>');
$('#myframe').attr('src', 'https://mywebsite.com/page2');
function myframe() {
var $myframesearch = $('#myframe').contents();
$myframesearch.find("a").attr('target','_parent');
}
$('#myframe').load(function(){
$('#loading').remove();
$('#myframe').fadeIn();
});
All of the links within iframe have no href (but href="javascript:void(0)") and uses scripts within iframe to process the action dynamically.
Some links does open in new window some does not.
I would like to force all links to either open in new Tab, Window, or append to new Div, but none of the methods work, like base / parent, onclick / new window, _top, _parent, etc.
However, my idea was to hide and wait till the content of iframe is loaded after a click and then to append loaded content in new hidden div and then fade it in. When doing so the loaded iframe content resets back to default and not with new content.
Does anyone knows how this can be solved?
Thank you all!
So I check and it appears that other JavaScript overwrites the "a" tag action with some "data" field in the tag only for the "a" tags that contain "Open:" in their link.
I found solution to the problem below by the link for this "a" tag from another page bypassing the JavaScript overwriting:
$(function(){
$('#mydiv').append('<p id="loading">Loading ...</p>');
$('#mydiv').append('<iframe id="myframe" name="myframe" class="myframe" src="https://mywebsite.com/page2" onload="myframe()" style="display:none;"></iframe>');
$('#myframe').load(function(){
$('#loading').hide();
$('#myframe').fadeIn();
});
$('<div id="popup" style="display:none; width:1px; height:1px; position:absolute; top:0; left:0;"></div>').appendTo('html');
});
function myframe() {
var $myframesearch = $('#myframe').contents();
$myframesearch.find("a").attr('target','_parent');
$myframesearch.find('a:contains("Open:")').on('click',function(){
$(this).attr('data','');
var $texta = $(this).text();
var $text = $texta.replace(/Open: /,"");
$('#popup').load('https://mywebsite.com/page2' + ' a:contains("'+$text+'")', function(){
$('#popup a').each(function(){
this.href = this.href.replace(/https:\/\/mywebsite\.com\/page2\/a/, "https://mywebsite.com/page2");
this.click();
});
});
});
}
Hope this helps :)

Change Twitter Widget appearance on-the-fly

I have the following code in my document:
<a class="twitter-widget" href="url" data-widget-id="138843679974442730">Twitter Timeline</a>
<script>!function(d,s,id){var js,fjs=d.getElementsByTagName(s)[0],p=/^http:/.test(d.location)?'http':'https';if(!d.getElementById(id)){js=d.createElement(s);js.id=id;js.src=p+"://platform.twitter.com/widgets.js";fjs.parentNode.insertBefore(js,fjs);}}(document,"script","twitter-wjs");</script>
data-widget-id is connected to one style. Right now if there is a theme change on the website (I replace all responsible stylesheets and images) everything changes but the Twitter widget.
Since the widget itself is an iframe, I can't change any stylesheets attached to it.
Is there an easy way to change the style of the widget without reloading it (deleting the tag, creating the tag, running js)?
You can style elements in the Twitter widget iframe using JavaScript.
First, you need the active document in the iframe's nested browsing context:
var doc = document.getElementById("twitter-widget-0").contentDocument;
Then, you can apply styles (e.g.):
doc.querySelector(".timeline-header").style["background-color"] = "black";
doc.querySelector(".timeline-header a").style["color"] = "white";
Example: http://codepen.io/smockle/pen/IJHnj
There is no straight forward way of doing this, so I've decided to bring in another dependency that will be delaying the onload event..
<script type="text/javascript" src="//platform.twitter.com/widgets.js"></script>
And here is the code that did the job:
var twitterBox = document.getElementsByClassName("twitterBox");
if (!twitterBox || twitterBox.length == 0) { return true; }
var twitterTimeline = document.createElement('a');
twitterTimeline.className = 'twitter-timeline';
twitterTimeline.href = 'url';
twitterTimeline.innerHTML = 'Twitter Timeline';
twitterTimeline.setAttribute('data-widget-id', '388742673974046720');
twitterBox[0].removeAttribute('data-twttr-id');
twitterBox[0].innerHTML = '';
twitterBox[0].appendChild(twitterTimeline);
twttr.widgets.load();

Force iframe to evaluate its javascript?

I'm dynamically creating an iframe and at some point I need to insert javascript into it. I can add the tag with the string just fine, but is there a way to force the iframe to re-evaluate its scripts so the javascript is executable?
Simple example of what needs to be done is, user provides:
<h2 onclick="doSomething();">Click me</h2>
and
function doSomething() { alert('you clicked me'); }
I need to push the html into the body of the iframe, and I need to push the javascript string into the scripts of the iframe in a way that will allow this to work.
HTML
<!--Container of iframe, iframe will be appended to this div later-->
​<div id='myDiv'>​</div>​
JS
var iframe = document.createElement('iframe');
iframe.frameBorder = 1;
iframe.width = "500px";
iframe.height = "250px";
iframe.id = "iframe";
iframe.onload = function()
{
var doc = iframe.contentDocument || iframe.contentWindow.document;
var el = doc.createElement('h2');
el.id="myH2";
el.className="red";
el.style.color="red";
el.style.cursor="pointer";
el.textContent = "Click me";
el.onclick=doSomething;
doc.body.appendChild(el);
}
document.getElementById("myDiv").appendChild(iframe);
function doSomething()
{
alert("OK");
}​
Here is a fiddle.
If you change onclick="doSomething();" to onclick="top.doSomething(); it will work. Because copied h2 looks doSomething function on current window, and in iframe there is no doSomething function.
If you use top keyword, it will look function in top window. In iframe that means look for parent, and in parent look for self, and it will work in parent and in iframe either. Unless there is no another parent exists.

Categories