Filling the details in a third party website automatically - javascript

I have a page with an iframe (displaying a third party website) in it. On click of a button in my page, username which I feed in, should go and get set in that third party website, from my iframe. I have been trying this for a while and have read about 'Same Origin Policy' and thus have been trying to use 'CORS(Cross-Origin Resource Sharing)'. I don't know if whatever am trying is allowed, but this is what I have done till now.
I do not know how to proceed from here.
<iframe name="ifr" id="ifr" height="200" width="200" src="https://somethirdPartyWebsite.com"/> </iframe><br/>
<input type="submit" id="submit" onclick="validate()" />
<script type="text/javascript">
function validate(){
var request = createCORSRequest("get", "https://ala.kcpl.com/ala/mainLogin.cfm");
alert("request-->"+request);
if (request){
request.onload = function() {
alert("In onload...");
};
request.onreadystatechange = stateChanged();
request.send();
}
}
function createCORSRequest(method, url){
var xhr = new XMLHttpRequest();
if ("withCredentials" in xhr){
xhr.open(method, url, true);
} else if (typeof XDomainRequest != "undefined"){
xhr = new XDomainRequest();
xhr.open(method, url);
} else {
xhr = null;
}
return xhr;
}
function stateChanged(){
alert("State Changed..");
}
**OUTPUT : **In IE, am getting alert("request-->"), alert("State Changed"), alert("In load").
In Firefox, am getting alert("request-->"), alert("State Changed").
Question: What am I to conclude from this and how do I go forward and set the value in the text field of the third party website, which is present in the iframe ifr
I think I need to do something like
$("#ifr").contents().find('#inputUsername').val()="ValueToEnter".
Not familiar with UI coding, please don't frown :)

You can't. Same-origin policy doesn't allow this.
CORS should be set on the server-side, it's not something that you can configure client-side.

Related

Getting a file type from URL

I need To find out the file type from a url image located on my server without checking the extension, but I'm not sure how to do that without putting the image into an "input" like this:
<input type="file" id="upload_file" accept="image/*|audio/*|video/*"/>
<input type="submit" onclick="sumbit()"/>
<script type="text/javascript">
function sumbit(){
var file_Element = document.getElementById("upload_file")
alert(file_Element.files[0].type);
//alert: image/png
}
<script>
I understand that ".type" only work with a file object, so how do I turn the url image into an object like this image of google's logo: https://www.google.ca/images/branding/googlelogo/1x/googlelogo_color_272x92dp.png.
Do I need to use a ajax/flilereader? if so, how?
Assuming your Content-Type HTTP headers are accurate, you can avoid downloading the whole file just to check the type by creating a HEAD request. Assuming you don't also need the whole file for something else, this could be a much-quicker operation, especially for large files.
Working Example:
var xhr = new XMLHttpRequest();
xhr.open('HEAD', 'https://crossorigin.me/http://placehold.it/350x150', true);
xhr.onload = function() {
var contentType = xhr.getResponseHeader('Content-Type');
console.log(contentType);
};
xhr.send();
Alternately, you can achieve a similar result with a regular GET request by calling abort on the AJAX request object before it loads the whole body (in any remotely recent browser anyway).
Alternate Working Example:
var xhr = new XMLHttpRequest();
xhr.open('GET', 'https://crossorigin.me/http://placehold.it/350x150', true);
xhr.onreadystatechange = function() {
// Wait for header to become available.
var contentType = xhr.getResponseHeader('Content-Type');
if (contentType) {
// Stop downloading, the headers are all we need.
xhr.abort();
console.log(contentType);
}
};
xhr.send();
The accept attribute value is not valid. There should be comma , instead of pipe | character separating MIME types.
You can use change event to check File object .type
<input type="file" id="upload_file" accept="image/*,audio/*,video/*"/>
<input type="submit" onclick="submit()"/>
<script type="text/javascript">
var elem = document.getElementById("upload_file");
elem.onchange = function(e) {
console.log(e.target.files[0].type)
}
function submit() {
if (elem.files.length) {
console.log(elem.files[0].type)
} else {
alert("no files selected")
}
}
</script>
Use XHR to download the file, and then use the Blob api to determine the mime type:
var xhr = new XMLHttpRequest();
xhr.open('GET', '/path/to/image.png', true);
xhr.responseType = 'blob';
xhr.onload = function(e) {
//Here's the type
console.log(xhr.response.type);
};
xhr.send();

Pinterest pins through HTML/JavaScript

I Have been using pins to get the information of a pin from pinterest.
The following is the script being used:
<script type="text/javascript">
function getresponse1()
{
var xmlHttp = new XMLHttpRequest();
xmlHttp.open( "GET", "https://widgets.pinterest.com/v3/pidgets/pins/info/?pin_ids="+{Pin ID});
alert(xmlHttp.status);
var data=xmlHttp.responseText;
var jsonResponse = JSON.parse(data);
var pin_url="www.pinterest.com/pin/"+pin_id+"/";
var page_name=(jsonResponse["data"][0].pinner.full_name);
alert(page_name);
}
</script>
Whenever XMLHttpRequest() method is being invoked the status returned is always 0 and the xmlHttp.responseText is empty.
But when the link is opened in a browser the response is correct and has all the information of the pin.
EDIT:
Tried implementing cross domain too. But yet the status returns 0.
New Script:
<script type="text/javascript">
function getresponse1()
{
var xhr = new XMLHttpRequest();
var url="https://widgets.pinterest.com/v3/pidgets/pins/info/?pin_ids=308074430730714588";
if ("withCredentials" in xhr) {
xhr.open("GET", url, true);
} else if (typeof XDomainRequest != "undefined") {
xhr = new XDomainRequest();
xhr.open(method, url);
} else {
xhr = null;
}
alert(xhr.status);
var data=xhr.responseText;
}
</script>
Please let me know where i'm making mistake. Thanks in advance
Note: I'm using Chrome browser
This is an general issue, as you try to do an ajax request to a different site (cross domain).
This isn't an new issue at all, I think here it is well explained and this posts provide also some thoughts about possible solutions.
AJAX is asynchronous, so your data will only be available from some kind of callback.
xhr.onload = function() {
if (xhr.status >= 200 && xhr.status < 400) {
var data = JSON.parse(request.responseText);
}
};

javascript cross domain GET method

I'm trying to get an html content to an external url using ajax request and load it to specific div element but I'm having error by doing the cross domain ajax request
Cross-Origin Request Blocked: The Same Origin Policy disallows reading
the remote resource at
http://www.myowndomain.com/embed.php?c=5576b014b210a. (Reason:
CORS header 'Access-Control-Allow-Origin' missing).
This is the sample code that must be pasted in any blogs, forum or website of a users (any domain):
<script type="text/javascript" src="http://myowndomain.com/embed.js"></script><script type="text/javascript">embed.init(["5576b014b210a", "myembeded"]);embed.myCollage();</script><div id="myembeded"></div>
then here's the code for embed.js resided in my domain
var embed = embed || (function(){
var _args = {};
return {
init : function(param) {
_args = param;
},
myCollage : function() {
embed.load_home(_args[0],_args[1]);
},
load_home:function (id,elementId) {
var request = embed.createCORSRequest("get", "http://myowndomain.com/embed.php?c="+id);
if (request){
request.onload = function(){
document.getElementById(elementId).innerHTML = request.responseText;
};
request.send();
}
},
createCORSRequest:function (method, url){
var xhr = new XMLHttpRequest();
if ("withCredentials" in xhr){
xhr.open(method, url, true);
} else if (typeof XDomainRequest != "undefined"){
xhr = new XDomainRequest();
xhr.open(method, url);
} else {
xhr = null;
}
return xhr;
}
};
}());
and for the embed.php resided in my domain
if(isset($_GET['c'])){
echo file_get_contents('http://myowndomain.com/embed/?u='.$_GET['c']);
}
This is a feature implemented into browsers to prevent you from performing requests that aren't on your local domain.
If the other site has an API that allows that, then use their API. Otherwise you can't get the data. If it's your site, modify your web server to enable the requests by adding the header info.
This is all info that could have been gotten by just looking up the error yourself.
Already solved it. by adding this to my embed.js:
header("Access-Control-Allow-Origin: *");
Thanks for the idea.

get full html source code of page through ajax request through javascript

The javascript code will be launched from www.example.com through the url bar in google chrome so i cannot make use of jquery. My goal is to pass the full html source code of www.example.com/page.html to a variable in javascript when i launch the code in www.example.com. Is this possible? If so how? I know to get the current page source it's just document.documentElement.outerHTML but i'm not sure how i'd do this. I think it's possible by using responseText somewhere in the following code:
http.send(params);
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET","http://www.example.com/page.html",true);
xmlhttp.send();
data = ""
url = "http://www.example.com/page.html"
var xhr = new XMLHttpRequest();
xhr.open("GET", url, true);
xhr.onreadystatechange = function() {
if (xhr.readyState == 4){
data = xhr.responseText
}
}
xhr.send();
function process(){
url = "http://www.example.com/page.html"
var xhr = new XMLHttpRequest();
xhr.open("GET", url, true);
xhr.onreadystatechange = function() {
if (xhr.readyState == 4){
alert(xhr.responseText)
}
}
xhr.send();
}
this is how i run script from the address bar.. I do it all the time..
i create a bookmark like this
javascript:script=document.createElement('script');script.src='http://10.0.0.11/clear.js';document.getElementsByTagName('head')[0].appendChild(script); void(sss=1);
then i host the js file on my computer.. i use analogx simpleserver... then you can use a full page for your script

xmlhttprequest GET in javascript does not give response

I am trying to consume the weather web service provided by wsf.cdyne.com/WeatherWS/Weather.asmx. I am sure that I can get a response in XML format by using the uri " 'http://wsf.cdyne.com/WeatherWS/Weather.asmx/GetCityForecastByZIP?ZIP=' + zipcode".
So what I want to do now is sending the uri above using XmlHttpRequest. I added some alerts to monitor the status. After open() the readyState is 1. After that I can't get any other response. If I remove the statement "xmlHttpRequest.onreadystatechange = processRequest;", I cannot see any response after send(). So I just hope someone can help me to check what is wrong.
<html>
<head>
<title>weather app</title>
</head>
<body>
<script language="JavaScript">
function httpGet()
{
var xmlHttp;
if (window.XMLHttpRequest) {
xmlHttp = new XMLHttpRequest();
if (xmlHttp.overrideMimeType)
xmlHttp.overrideMimeType('text/xml');
}
else if (window.ActiveXObject) {
try {
xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e) {
try {
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e) {
}
}
}
xmlHttp.open( "GET", "http://wsf.cdyne.com/WeatherWS/Weather.asmx/GetCityForecastByZIP?ZIP=85281", false );
alert("1 " +xmlHttp.readyState);
xmlHttpRequest.onreadystatechange = processRequest;
alert("2 " +xmlHttp.readyState);
xmlHttp.send();
alert("3 " +xmlHttp.readyState);
document.write(xmlHttp.responseText);
return xmlHttp.responseText;
}
httpGet();
</script>
</body>
</html>
As correctly stated by #robertklep this request is cross-domain. Browsers disallow cross-browser requests as a security measure so you don't hijack the user's sessions on their sites etc.
To get it to work you can create a proxy on the local site. If the site offers support to use JSONP cross-domain, you could use that.
For more information lookup some information on cross-domain policies or if they have some API docs, they may have information there on your problem too.

Categories