How to get reference to elements of an iframe? - javascript

Basically a survey from SurveyMonkey is loading on my webpage in an iframe.That survey has 'Done' button which needs to be clicked when you have filled up the survey. Now when i inspect console by right-clicking on page anywhere except survey pop up and execute this statement:
document.getElementsByClassName("btn small done-button survey-page-button user-generated notranslate");
The result i get is:
HTMLCollection []
But when i inspect on survey popup and write the same statement in console i get the following result:
HTMLCollection [button.btn.small.done-button.survey-page-button.user-generated.notranslate]
Basically i want to add an event when 'Done' button will be pressed but the problem is i cannot get reference to this button simply by passing its class because it loads after few seconds later when my html page is loaded.
I have even written a function to alert me 'Hi' when 'Done' button shows up button it is of no value.Here is the code:-
$('.btn small done-button survey-page-button user-generated notranslate').on('load',function(){alert('hi'); console.log("survey-loaded");});
Following is the html of 'Done' button:
<button type="submit" class="btn small done-button survey-page-button user-generated notranslate">DONE</button>

You cannot reference iFrame content from another domain. That will violate the Same-origin policy.
The mere idea of an iFrame is that it blocks you from manipulating its content, so the SurveyMonkey content still considered secured.
You can, however, interact with iFrame via post messages, and you can get a reference to iFrame content if it doesn't violate the same-origin policy.
See similar questions here, and here.

Try to access iframe elements after it is loaded.
document.getElementById('your-iframe-id').onload = function() {
// Create variable for your iframe.
var iframe = document.getElementById("your-iframe-id");
//then access its content like this
var btn document.getElementsByClassName("btn small done-button survey-page-button user-generated notranslate");
//Rest of your code
}
The above code will only works if there is no cross domain restriction

Use a delegate, target a parent element that is always on the page the the addEventListener to it
document.querySelector('your-const- parent- `element-containing-the- button').addEventListener('click',(e)=>{
If(e.target.tagName === 'BUTTON')
'your actions'}
);
I hope this helps #cheers

Related

How to trigger iFrame load within an iFrame?

I send messages to iFrame, but only on iFrame load event. Want to trigger it manually without page reload, after changing DOM.
Explanation: It is kind of survey and on page change I send page size. Problem happens when I insert new image in DOM, than I need to tell parent page and trigger the iFrame load event. The message goes parent->iframe, than iframe->parent only on iFrame load.
Instead of triggering a load event, you should use a message posted by your IFrame.
JavaScript in outer frame (this attaches an event listener for messages and shows an alert when a message is received):
window.addEventListener('message', function(e) {
// This check can be removed for testing purposes, but for security
// it's strongly recommended that you leave it in there and replace
// the domain with the one of your IFrame's src, to ensure you process
// only messages coming from your own code and not somebody else's.
if(e.origin != "http://yourdomain.com") return;
alert("Got a message: " + e.data);
});
JavaScript in inner frame (this sends a message to the parent window - it should trigger the listener there and show the alert):
// The second parameter can be replaced by "*" for testing, but again it
// is strongly recommended to use the domain you expect the outer frame
// to have, to ensure your message lands in the right window (in case
// another page loaded yours in an IFrame).
window.parent.postMessage("Hello World!", "http://yourdomain.com");
Instead of "Hello World!", you can also pass JS objects.
It also works the other way round: If you install a message listener in your IFrame as well, then you can also send messages from the outer frame to the inner one, using something like document.getElementById('myIframe').contentWindow.postMessage(...).
See also: http://blog.teamtreehouse.com/cross-domain-messaging-with-postmessage

Javascript function onclick, back button to "refresh" page

I have looked around, but I'm not seeing anything that specifically addresses this. My goal is to have a link, which can be clicked to either add content or "undo" the act of adding that content. I am trying to us the following:
function ShowDiv() {
if (null == window.set) {
document.getElementById("box2").innerHTML = "Some Content";
window.set = "set";
} else
location.reload();
}
Link
<div id="box2"></div>
This allows me to click the link to show some content inside some div. And then to click the link again to remove that content.
However, I am wondering if there is a way to achieve this result, that also allows the user to click the browser's back button to return the page to the state it was in before triggering the function (e.g., to reload the page).
You are looking for the HTML5 history API. This allows you to push state onto the history as if the browser loaded a different location without actually sending a request and replacing all content and javascript state. This allows the back and forward buttons to work, as long as your JavaScript code shows the correct content according to the current URL.
Resources:
W3C
MDN
Dive Into HTML5

Closing an iframe after it has reloaded another html page

I have made the following site:
www.ppp.one
Whenever you open an image, a popup is loaded.
This popup can be closed using the X on the top-right. However, if you click on one of the thumbnails in the popup (reloading the frame) the X button can no longer close it.
The JavaScript I use:
function hide(){
if(currentIframe){
currentIframe.hide();
currentIframe = null;
}
popupBG.remove();
popup.remove();
}
And the html:
<a class="small align-top" onclick="frameWarp.hide();">&#10006</a>
Any ideas on what is causing the issue?
When you open the popup you call a function setUpAPI which inserts the frameWrap object into the global scope of the iframe.
When a thumbnail is clicked the frame is reloaded and the frameWrap instance is no longer available.
You could try listening for load events on the iframe instead of ready events:
iframe.ready(function(){
frameCacheDiv.append(iframe);
});
iframe.load(function(){
setUpAPI(iframe, settings);
settings.onShow();
});
It looks like when the iframe's URL changes the frameWarp variable becomes undefined. One idea to try would be to listen to the load event of the iframe and make your changes there: (you'd have to give it the ID of "iframeId")
$('#iframeId').load(function(){
console.log('URL changed');
// code to attach hide event here
});
Another idea would be to change your setup to use the postMessage API for the communication between the parent and iframe. You can read a tutorial of how to do that here:
http://robertnyman.com/html5/postMessage/postMessage.html
Edit: Actually, this blog post is a better example: http://davidwalsh.name/window-iframe

AJAX crawling on single page

I was really confused with this question despite on google guide.
So, I have a web-page(html and js) which is upload some information to the
<div id=""></div>
using jquery's
.load(target)
Uploading realized with js function and "onclick" event in the html document.
So, when I click on the page region js start to upload information to the block.
According to google guide I should to use hash-bang if I want that page will be crawl.
Questions:
1.How can I implement this considering I have only one page?
2.How can I give access to the "#!" pages which upload by script?
3.How can I create html snapshots?
Thank you.
regarding Your question:
lets assume you have a page named MyPage.html with 3 elements to which you attach java script, with id's: A, B, C. each one of them causes different content to load in your div.
1) the simplest way is to create links like:
<a id='A' href='#GoToA' onclick='javascript:executeYourCodeA();'>Load A</a>
<a id='B' href='#GoToB' onclick='javascript:executeYourCodeB();'>Load B</a>
<a id='C' href='#GotoC' onclick='javascript:executeYourCodeC();'>Load C</a>
what that would do is when user clicks the link, the '#GoToA'or other will be added autommatically to browsers page addres. So the page address will look like
www.yourdomain.com/MyPage.html#GotoA
this change in addres will be remebered by the browser in its history.
2) if you wan to read the url use
var mylocation = window.location
- source: http://www.w3schools.com/js/js_window_location.asp
3) if the user accesses only MyPage.html everything is ok, the page renders with its original state, but what if user wants to see content visible after clicking link A ?
You can tell the difference, on page load, reading page url ( see 2)) and automatically loading the content. it can be achieved by :
$(function (){
var myurl = window.location;
var target = myurl.split('#')[1];
switch(target){
case 'GoToA' : executeYourCodeA(); break;
case 'GotoB' : executeYourCodeB(); break;
.
.
default: /*show the original, initial page*/
break;
});
Effectively what's going on now is that loading an address MyPage.html and clicking link A is the same by means of what is displayed to accessing a page MyPage.html#GoToA
So this way you can have separate links to the same site with different dynamically loaded content.
The thing Cristian Varga told you about can be used to achieving back and forward capabilities: basically what you do is you create a normal link to a page like MySecondPage.html ( this page does not really exist ). You then on click event load the contents to your div, force stop execution of standard link behavior (by preventDefault() - this causes your event not to be processed any more - so the browser 'ignores' navigation to MySecondPage.html. You then manually tell the browser to store the history stete and tell it that you are now om MySecondPage.html
history.pushState(null, null, link.href);
so you load the content, block navigation and manually convince the browser that the page has changed and to store the state in browsers history.
but now achieving the snapshot capability - would be more tricky in my mind, as the MySecondPage.html is a perfectly valid but non existent url, loading MyPage.html instead when user types in www.mydomain.com/MySecondPage.html and displaying MySecondPage content would require server side actions.
- source http://diveintohtml5.info/history.html

Html to fire an event

Can anyone help with this please?
I have a webpage with an asp.net frame on it- the frame shows the contents of an html document.
When someone clicks on a link in the html document, I need to show some content in another frame on the same page.
So, the question is, what should 'myTag' be in the following...
e.g.
//this is the contents of my html file`
<p>to be or not to be, <myTag>that</myTag> is the question</p>
Whatever 'myTag' is (maybe a piece of javascript? don't know), it should be able to fire an event on the server so I can send some more text to the other frame on the page
Any ideas?
thanks..
The first thing I would do is give the other frame an ID or some way to easily get to it with javascript. Then inside your iframe, you could do something like:
var other_frame_document = window.parent.document.getElementById('other_frame').contentWindow.document;
// example 1: set the HTML of the other frame from a string.
// this is usually a bad idea because of XSS.
other_frame_document.body.innerHTML = '<b>aloha</b>';
// example 2: better way is to manipulate the DOM in the other iframe
var elm = other_frame_document.createElement('b');
elm.appendChild(other_frame_document.createTextNode('aloha'));
other_frame_document.body.appendChild(elm);
that is one way to fire an action.
Or you can bind the action using jQuery (or some other library) when the DOM loads, like this:
jQuery("#myTagId").bind("click", function() { ... });
This will cause the event to fire when the element is clicked.
You can then use ajax to call the server to update the other frame.

Categories

Resources