Can't get iframe content - javascript

I know there are many topics about it, but none of them worked. I need just to get iframe content(not source code).
I have a form, that posts some parameters to another server and I target it to iframe(that lies on the same page). So I receive server responce code storred in my iframe without page refresh:
<form name='vin_form' id='file_upload_form' action='*****' method='post'>
<input name='name1' value='value1'>
<input name='name2' value='value2' type='hidden'>
<input name='name3' value='value3' type='hidden'>
<div onclick=\"document.getElementById('file_upload_form').target = 'upload_target'; document.vin_form.submit();\">Send form</div>
</form>";
<iframe id='upload_target' name='upload_target'></iframe>
To get iframe content I used everything, but nothing worked:
jQuery('#upload_target').load(function()
{
alert(jQuery('#upload_target').contents().find('body').html());
var myIFrame = document.getElementById('upload_target');
var content = myIFrame.contentWindow.document.body.innerHTML;
alert(content);
alert(window.frames.upload_target.document.body);
}
);
I read about "same origin policy", but I think it shouldn't be forbidden in my case, because I can access that page by url and read all the code, so why I can't do it programmatically?
P.S.: Are there some other ways to get form responce code from another server? (php curl doesn't work because of some site framework defence)

*update - try this:
var t = document.getElementById("upload_target");
var y =( t.contentWindow || t.contentDocument);
alert(y.document.body.innerHTML)

Related

Getting around CORS with embedded google forms

I'm trying to send form data to google via an embedded form.
I found this post that seems to answer my question but I'm getting CORS errors. Is there a way to solve this?
Other posts seem to say that CORS isn't an issue but I'm getting the errors.
Here is my code:
-JS-
function ajax_post() {
var field1 = $('#email').val();
$.ajax({
url: "https://docs.google.com/forms/d/e/xxxxxxxxxxxxxxxxxxxxxx/formResponse",
data: {"entry.xxxxxxxxxx": field1},
type: "POST",
dataType: "xml",
statusCode: {
0: function() {
//Success message
},
200: function() {
//Success Message
}
}
});
}
-HTML-
<form id="emailForm" target="_self" onsubmit="" action="javascript: ajax_post()">
<input id="email" type="text" autocomplete="off" tabindex="0" name="entry.xxxxxxxxxx" required>
<button id="send" type="submit">Submit</button>
</form>
The “No 'Access-Control-Allow-Origin' header is present on the requested resource” message indicates that responses from https://docs.google.com/forms/d/e/xxxx/formResponse URLs currently don’t include the Access-Control-Allow-Origin response header, so browsers won’t allow your frontend JavaScript code to access the response.
Given that, from your frontend code there’s no way you can tell if the POST request succeeds or not. But barring any other problems, it seems like the request will always succeed. If the request doesn’t reach the server at all (due to some network error) then you’ll hit a different failure condition that is observable from your frontend code so you can actually catch it.
So the way you know the request has successfully reached the server is just that you don’t get any other failure that’s observable from your frontend code.
I've found that it's actually easier to just POST the form with a hidden iframe as its target, and capture that iframe reload when the response is submitted.
For example, if this is your form:
<form id="my-form" target="my-response-iframe" action="https://docs.google.com/forms/u/1/d/e/<YOUR-ID>/formResponse" method="post">
<input type="text" name="entry.12345678" value="" required>
<input type="submit">
</form>
Then include an iframe on the same page, with the same id AND name you put as target in the form:
<iframe id="my-response-iframe" name="my-response-iframe"></iframe>
When the form is submitted, it should reload that iframe with the "Your response has been recorded." page from Google. We can catch that reload with JavaScript, so include this after your form and iframe:
<script type="text/javascript">
// set the target on the form to point to a hidden iframe
// some browsers need the target set via JavaScript, no idea why...
document.getElementById('my-form').target = 'my-response-iframe';
// detect when the iframe reloads
var iframe = document.getElementById('my-response-iframe');
if (iframe) {
iframe.onload = function () {
// now you can do stuff, such as displaying a message or redirecting to a new page.
}
}
</script>
You can't check whether the response was submitted correctly because you can't inspect the contents of a cross-origin iframe (that'd be a huge security risk), so just assume that if this iframe reloads, the response was ok.
You can hide the iframe with the following CSS:
visibility: hidden
height: 1px;
Much cleaner if you ask me, with no console errors or failed requests.

Having problems with my very basic HTML static page generator

I am trying to create a new HTML page from a form and some javascript. The form is much longer than this, but I figured that if I gave you guys 2 text inputs I can take it from there. I am running into a problem where I cannot retrieve the value of my forms and send it on to my new page. My new page won't show anything because it thinks that my forms are null, or that they don't exist possible. Which is probably why it returns undefined. I'm completely stuck here and I have no idea what to do as far as setting up the new page from my form goes.
I need help with getting newPage.html to display my title and subtitle.
Here is js:
var title = document.createElement("h1");
var titleForm = document.getElementById("title");
var subTitle = document.createElement("h3");
var subtitleForm = document.getElementById("subtitle");
var myDiv = document.getElementById("container");
function getElements() {
//set the title
var titleNode = document.createTextNode(titleForm.value);
title.appendChild(titleNode);
//set the subtitle optionally
var subtitleNode = document.createTextNode(subtitleForm.value);
subTitle.appendChild(subtitleNode);
}
Here is the original HTML page:
<body>
<h1>Create A New Webpage Using This Form</h1>
<form id="form">
<label>
Title:
<input type="text" name="title" id="title" value="title">
</label><br><br>
<label>
Subtitle:
<input type="text" name="subtitle" id="subtitle" value="subtitle">
</label><br><br>
<input type="button" value="Generate Page" onclick="window.open('newPage.html');">
</form>
<script type="text/javascript" src="pageGenerator.js"></script>
<script>getElements();</script>
</body>
Here is the page that I want to create:
<body>
<div id="container">
<ul id="myList"></ul></div>
<script type="text/javascript" src="pageGenerator.js"></script>
<script>setElements();</script>
</body>
I'm not looking for you to complete this for me, but just a little bit of guidance. Thanks.
It sounds like you want JavaScript on one page to read from JavaScript on another page. That's not possible on its own. You can't define var a = 1 on somePage.html then read that variable when the user's browser loads newPage.html.
You'll need to involve something else, such as the URL or local storage: https://stackoverflow.com/a/35027577/5941574
Query Parameters
One option is to make a GET request to newPage.html with whatever values you want include as query parameters in the request. Then newPage.html will contain a script that parses the URL to get the parameters and builds and inserts HTML into the document based on the values it finds in the URL.
Local Storage or Cookies
This works in pretty much the same way as the other method except instead of getting your values from the URL, it is saved to the user's computer with either cookies or local storage.
Server Side
A third option of course is to send the user's selections to a server and have the server build and serve the resulting page.

Set value of input field inside an external iframe

I know this have been asked so many times but everyone ask it to suite his own need so couldn't find answer that help me
I have two sites and have access to both and can add whatever I need inside both sites
my first site
http://www.mysite1.com
on this site
I have text field with specific value
I have an iFrame whose content are sourced from my other website.
<input type='text' name='test1' value='5'>
<iframe name='myframe' src='http://www.mysite2.com/index.php'></iframe>
on this page
http://www.mysite2.com/index.php
I have input text field
What I am trying to achieve is :
getting the specific value from my first site to the input field in my second site
Since that manipulating frames that have a different origin will cause a Cross-Origin error to occur, you'll have to use the window.postMessage() method to send a message to the child <iframe> and, inside it, listen to window.onmessage and handle the message.
Here is an example, supposing you have got a DOM structure like this:
Site #1 (www.mysite1.com):
<body>
<iframe id="site2-frame" src="http://www.mysite2.com/index.php"></iframe>
</body>
Site #2 (www.mysite2.com) in the iframe:
<body>
<input id="input-field" />
</body>
Then in your site #1 you'll have to send a message to the frame, like this:
var frame = document.getElementById('site2-frame');
frame.contentWindow.postMessage('Something something something', '*');
And in your site #2, the one inside the frame, you'll listen to the message and set the data:
var input = document.getElementById('input-field');
window.addEventListener('message', function(e) {
// Check the origin, accept messages only if they are from YOUR site!
if (/^http\:\/\/www\.mysite1\.com/.test(e.origin)) {
input.value = e.data;
// This will be 'Something something something'
}
});
JCOC611 is right. In modern web development Window.postMessage is the way to go. Selecting elements within the iframe and changing their value will very like cause cross-origin security errors – for good reasons.
Here is an example, how you could realize exchanging a value across site/iframe using the postMessage event pattern:
<script>
window.onload = function(){
// Define the target
var win = document.getElementById('iframe').contentWindow;
// Define the event trigger
document.getElementById('form').onsubmit = function(e){
// Define source value or message
win.postMessage(document.getElementById('source').value);
e.preventDefault();
};
};
</script>
<form id='form'>
<input id="source" type='text' value='5'>
<input type='submit'/>
</form>
<iframe name='myframe' src='http://www.mysite2.com/index.php'>
<!-- This is what happens inside the iframe -->
<form id='form'>
<input id='target' type='text' value=''>
</form>
<script>
// Wait for the message
document.addEventListener('message', function(e){
// When you receive the message, add it to the target
document.getElementById('target').textContent = e.data;
}, false);
</script>
</iframe>
You can always send vars using iframe url query string name value pairs, and then on page load populate the variables or input fields as you desire.

Accessing element inside iFrame returning null

I have a form that posts to an iFrame. The website inside the iFrame is something I have no control over. However I would like to set the display of a few images inside the iframe to "none".
<form id="testForm" method="post" target="testFrame">
<input type="hidden" name="RequestXML" ID="RequestXML" value="<Request><RedirectURL>Account/TokenRequest</RedirectURL></Request>"
</form>
<iframe id="testFrame" name="testFrame" frameborder="0" style="width:1000px;height:500px"> </iframe>
Here is my script at the top of the page:
<script type="text/javascript">
$(function () {
$("#testForm").attr("action", "http://externalwebsite.aspx");
$('#testForm').submit();
var iframe = document.getElementById('testFrame');
var innerDoc = iframe.contentDocument || iframe.contentWindow.document;
//alert($("#testFrame").contents().find("body").html());
//alert(innerDoc.innerHTML);
});
</script>
Both my alerts return null in Chrome, IE and firefox. What is the best way to access the elements inside that iframe. (in chrome i dont even see the html of that website when I try to do "inspect element" and view the html)
By the way I am doing all this in a MVC4 project
Assuming this is not a cross-domain issue, try:
var body = $('#testFrame').contents().find('body');
Since this cross domain you have two options.
if you have access to the iframe code, then you can place XDM code in there, maybe easyXDM would help.
Or
you have to go server side and get your php/asp.net etc backend to go get the page and get what data it needs.

to send a text file to server using javascript

I need to send a text file to server and get it saved. how can i do it using javascript???
There are all sorts of security issues surrounding this. Would you be happy to visit a website that would upload a file from your machine to the server?
For a generic website, where users are likely to have their permissions set to deny this sort of access it isn't possible.
If by chance, you are looking to do this for an application where you have control over the security settings for its users, and that you can guarantee its Windows and IE, then it is possible by reading the file and passing the details by posting to the server. See the following link : http://www.javascripter.net/faq/reading2.htm
However when you move away from IE or Windows, then you are going to struggle.
using ajax of course.
have a file on the server, PHP or ASP - depending on what your internet server is.
this file will accept the text file (data and name), and should also check for size and if this file already exists or not, and if all is ok- it will save it, and return a string "OK"
on the client, javascript side, just send the information to the server using ajax, or HTTPREQUST object - there's plentty of documentation for that around. and if you get back a response of "OK" then you know that it sent well.
even better: don't use HTTPREQUEST, but do dynmaic script tag insertion - where the source attribute of the script you're appending is that file on the server like:
var a = document.createElement('script');
a.type = 'text/javascript';
a.src = "http://server/serverFile.PHP?filename=XXX&data=LONG STRING OF DATA REPRESTING THE DATA TO BE SAVED PROBABLY LESS THAN 2K IN SIZE AND ALSO YOU SHOULD ESCAPE OR ATLEAST URIENCODE IT";
document.body.appendChild(a);
and on the server file, serverFILE.PHP:
<?php
// some code to save the request variable [data].
// if all is ok:
alert("ok")
// or:
result = "ok"
?>
get it?
note: you'll probably have a limit of less than 2K on the file size.
Javascript is a front-end language. You may use php or any server side language.
You can create an Ajax equiv function make an iframe with width and height=0px then make it the target of the form with the file upload input and process it with the action PHP
<form action="upload.php" target="target" method="post"
name="uploadform" id="uploadform" enctype="multipart/form-data">
<label for="input_file_upload">Upload:</label>
<input onchange="document.uploadform.submit();" size="80"
type="file" name="file_upload[]" id="file_upload"
multiple="multiple" />
<input type="hidden" name="fileUpload" value="upload" />
<input type="button" value="Upload" />
</form>
<iframe id="target" name="target" style="width: 0px; height: 0px;">
</iframe>

Categories