I'm currently developing a chrome extension, I need to access some http-auth protected resources (webdav). The HTTP auth is using (in the best case) a digest authentication.
The issue is : if the login/password is wrong, I can't just get a 401 status (unauthorized), Chrome pops up the regular authentication dialog. Which I don't want cause it's confusing for user and I can't save the credentials from here.
EDIT: Another use-case I faced is : I want to check if a resource is password-protected without trying to provide credentials to actualy access it.
Any ideas on how to catch the 401 without poping the Chrome's auth box ?
I try using this function:
function autoLogin(domain, user, password) {
var httpAuth;
if (window.XMLHttpRequest) {
httpAuth = new XMLHttpRequest(); // code for IE7+, Firefox, Chrome, Opera, Safari
}
else if (window.ActiveXObject) {
httpAuth = new ActiveXObject("Microsoft.XMLHTTP"); // code for IE6, IE5
}
else {
alert("Seu browser não suporta autenticação xml. Favor autenticar no popup!");
}
var userName = domain + "\\" + user;
httpAuth.open("GET", "/_layouts/settings.aspx", false, userName, password);
httpAuth.onreadystatechange = function () {
if (httpAuth.status == 401) {
alert("wrong");
eraseCookie('AutoLoginCookieUserControl_User');
eraseCookie('AutoLoginCookieUserControl_Password');
}
else {
if ($(".pnlLogin").is(':visible')) {
$(".pnlLogin").hide();
$(".pnlUsuario").css("display", "block");
$(".avatar").css("display", "block");
var name = $().SPServices.SPGetCurrentUser({ fieldName: "Title" });
$(".loginNomeUsuario").html("Seja Bem Vindo(a) <br />" + name);
}
}
}
try {
httpAuth.send();
}
catch (err) {
console.log(err);
}
}
Related
I have an e-commerce simulation web app for buying movies and I want a popup small window to appear when a user mouses over the movie's id and display info and give them the option to add that movie to their cart (like how Facebook displays users info when you mouseover one of your friend's names). I have a java servlet that receives the movie's id and gets the proper info from my database and sends it back to the JSP, but form there I don't know how to properly use AJAX or jquery to display the window with the proper info.
SERVLET CODE
int movie_id = Integer.parseInt((String) request.getParameter("movie_id"));
StringBuilder query = new StringBuilder("select * from movies where movies.id =");
query.append(movie_id);
// Perform the query
MySQLHandler sql_handler = new MySQLHandler( );
sql_handler.execute_query( query.toString() );
ResultSet result = sql_handler.get_result();
try {
Movie movie = createMovie(result);
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println(movie.getTitle());
request.setAttribute("movie", movie);
}
catch(SQLException e) {
e.printStackTrace();
}
}
JAVASCRIPT CODE
function ajaxFunction(movie_id){
var ajaxRequest; // The variable that makes Ajax possible!
try{
// Opera 8.0+, Firefox, Safari
ajaxRequest = new XMLHttpRequest();
} catch (e){
// Internet Explorer Browsers
try{
ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try{
ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e){
// Something went wrong
alert("Your browser broke!");
return false;
}
}
}
// Create a function that will receive data sent from the server
ajaxRequest.onreadystatechange = function(){
if(ajaxRequest.readyState == 4){
alert(ajaxRequest.responseText);
}
}
alert(movie_id);
var parameter = "movie_id=" + movie_id;
ajaxRequest.open("POST","MoviePopUpWindowServlet", true);
ajaxRequest.setRequestHeader("Content-type"
, "application/x-www-form-urlencoded") //Needed for post request for some reason. //http://www.javascriptkit.com/dhtmltutors/ajaxgetpost2.shtml
ajaxRequest.send(parameter);
}
$.ajax({
url: 'route/to/videoinfo' + specificVideoId,
type: "POST",
contentType: "application/json ;charset=UTF-8",
}).done(function(result){
(if you rendered out the html already just do)
var containerDiv = document.getElementById("#idOfDivToFill")
containerDiv.innerHTML = result
}).fail(function(err){
console.log(err)
})
Someone let me know if this is terrible.
I'm fairly new to the world of web development and am trying to read a txt file in internet explorer 8 and compare it to source code of a website to see if they are equal. This is so I can work out if the web page is functioning correctly.
I managed to get the source code with an xmlhttprequest and have tried the same to get the text file (which is in the same domain as my web page) and I am getting an access denied error.
After some research I can see that cross-domain xmlhttprequests won't work but that's not what I'm trying to do so I'm not sure how to proceed.
Having run the same code in Firefox(current version). It will read the file but not the web page!
I don't mind which of the two browsers I end up using but at the moment each does half of what I want it to.
my code is:
function source1(){
xmlhttp=new XMLHttpRequest();
xmlhttp.open("GET", "http://website",true);
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState==4) {
document.getElementById('textzone').value = xmlhttp.responseText
var inputString = xmlhttp.responseText;
alert(inputString);
comparison(inputString)
}
}
xmlhttp.send(null)
}
function comparison(inputString){
xmlhttp1=new XMLHttpRequest();
xmlhttp1.open("GET", "comparisondoc.txt", false);
xmlhttp1.onreadystatechange=function() {
if (xmlhttp1.readyState==4) {
var compareString = xmlhttp1.responseText;
alert(compareString)
if(inputString==compareString){
alert("Strings are equal");
}
}
}
xmlhttp.send(null)
}
All I need to know is why either the file won't open in ie8, or why the website source code shows up blank (in the alert) in firefox. Any help would be appreciated.
It could be a browser support issue.
Try the following code to initialize your XMLHttpRequest :
function createRequest() {
try {
request = new XMLHttpRequest();
} catch (trymicrosoft) {
try {
request = new ActiveXObject("Msxml2.XMLHTTP");
} catch (othermicrosoft) {
try {
request = new ActiveXObject("Microsoft.XMLHTTP");
} catch (failed) {
request = false;
}
}
}
if (!request)
alert("Error initializing XMLHttpRequest!");
}
Check your comparison function. You should you xmlhttp1 instead of xmlhttp at 2 places
function comparison(inputString){
xmlhttp1=new XMLHttpRequest();
xmlhttp1.open("GET", "comparisondoc.txt", false);
xmlhttp1.onreadystatechange=function() {
if (xmlhttp1.readyState==4) {
<!--alert(xmlhttp1.responseText)-->
var compareString = xmlhttp1.responseText;
alert(compareString)
if(inputString==compareString){
alert("Strings are equal");
}
}
}
xmlhttp1.send(null)
}
Try to add the if(xmlhttp.status == 200) { } stuff. Remember both of these are looping through status' "AND" readystates.
Technically you could be erroring somewhere (I'd rather not speculate on) halting progress to next request or whatever without the status check.
Also you "should" try other request techniques. ie.. xmlhttp.onreadystatechange = function(){itsReady(inputString)}; // we keep this line short and simple calling to another func that contains your status and readystate checks, response stuff, and more func.
On a pretty normal run the Loop looks like:
hi rdySte:1///status 0////////
hi rdySte:2///status 200////////
hi rdySte:3///status 200////////
hi rdySte:4///status 200////////
I ran into a lot of weird issues trying the long onreadystatechange = function (){ ... All stuff..} I successfully run a crazy set of request functionalities using the short onreadystatechange technique.
I noticed at the last minute->
is there a reason why the async flags are different between your funcs? I'd set them all to true unless you have a great reason.
This will work: (to test: 2 pages t1.php contains a num or whatever and t2.txt that has a num in sam dir as the funcs are called in)
function source1(){
var avar = 1;
xmlhttp=new XMLHttpRequest();
xmlhttp.open("GET", "t1.php",true); // shortened f-names for ease of test
xmlhttp.onreadystatechange = function(){jsg_snd(avar)};
xmlhttp.send(null)
}
function jsg_snd(avar){
if (xmlhttp.readyState==4) {
if (xmlhttp.status == 200) {
var inputString = xmlhttp.responseText;
document.getElementById('text_zone').innerHTML = inputString;
document.getElementById('text_zone1').value = inputString;
// alert(inputString);//
comparison(inputString)
}
}
}
function comparison(inputString){
xmlhttp1=new XMLHttpRequest();
xmlhttp1.open("GET", "t2.txt", true);
xmlhttp1.onreadystatechange= function(){jsg_snd1(inputString);};
xmlhttp1.send(null)
}
function jsg_snd1(inputString){
if (xmlhttp1.readyState==4) {
if (xmlhttp1.status == 200) {
var compareString = xmlhttp1.responseText;
//alert(compareString)
if(inputString==compareString){
//alert("Strings are equal");
document.getElementById('text_zone').innerHTML += "; Ok "+inputString+"=="+compareString+"";
}
}
}
}
Now the html in your body should look like:
<tt id = 'text_go' onMouseUp="source1();" >Go!</tt>
<tt id = 'text_zone' onMouseUp="text_zone.innerHTML = '';" >Click to clear!</tt>
<input type ='text' id = 'text_zone1' onMouseUp="text_zone1.value = '';" value = 'Click to clear!' >
The extra stuf is for ___s & giggles.
I have to call Rest Services using Javascript. My code is:
function CreateXMLHttpRequest() {
if (typeof XMLHttpRequest != "undefined") {
return new XMLHttpRequest();
} else if (typeof ActiveXObject != "undefined") {
return new ActiveXObject("Microsoft.XMLHTTP");
} else {
throw new Error("XMLHttpRequestnot supported");
}
}
function CallWebService() {
objXMLHttpRequest = CreateXMLHttpRequest();
objXMLHttpRequest.open("POST", "http://www.rest.net/services/abc.svc/json/GetXml", true);
objXMLHttpRequest.setRequestHeader("Content-Type", "application/xml;charset=UTF-8");
var packet = '<?xml version="1.0" encoding="utf-8" ?><CompanyRequest xmlns="http://schemas.datacontract.org/2004/07/abc.DomainModel" xmlns:i="http://www.w3.org/2001/XMLSchema-instance"><CompanyName>company</CompanyName></CompanyRequest>';
objXMLHttpRequest.onreadystatechange = function () {
if (objXMLHttpRequest.readyState == 4&&objXMLHttpRequest.status==200) {
alert(objXMLHttpRequest.responseText);
}
}
objXMLHttpRequest.send(packet);
}
The status is 200 in IE and I am able to get a response. But in Firefox and Chrome, the status is 0. How can I overcome this problem?
Thanks in advance.
You are requesting a document at http://www.rest.net and I assume you are on a different domain. In this case you are victim of the same origin policy and your calls are blocked.
It might work in IE if you have set http://www.rest.net as a trusted domain.
I do request:
And I receive XML:
<?xml version="1.0" encoding="UTF-8"?>
<search>
<location id="18171" client_id="511">
<site>3</site>
.....
After refresh browser I receive:
<?xml version="1.0" encoding="UTF-8"?>
</search>
Only If i close and open browser I receive
<?xml version="1.0" encoding="UTF-8"?>
<search>
<location id="18171" client_id="511">
<site>3</site>
Why? I don't want to close and open browser everytime
Thank you
My code:
function makeRequestXML(url) {
http_request = false;
if (window.XMLHttpRequest) { // Mozilla, Safari,...
http_request = new XMLHttpRequest();
if (http_request.overrideMimeType) {
http_request.overrideMimeType('text/xml');
}
} else if (window.ActiveXObject) { // IE
try {
http_request = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
http_request = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {}
}
}
if (!http_request) {
alert('Giving up :( Cannot create an XMLHTTP instance');
return false;
}
http_request.onreadystatechange = ContentsXML;
http_request.open('GET', url, true);
http_request.send(null);
}
function ContentsXML() {
if (http_request.readyState == 4) {
if (http_request.status == 200) {
number_checkbox = 0;
var xmldoc = http_request.responseXML;
This a problem with your server you are connecting to. I have no idea what it's doing, or what you expect it to be doing, but your JS is clearly hitting that server and returning data in all cases. If you are getting back bad data, that is not the fault of your JS.
It seems like the server may be sending different data based on the browser session, and relaunching the browser may reset that session.
is there an easy way to detect from a Chrome extension that the user is logged into his google account or not.
I guess there is a nasty way to figure this out by loading a html/css/js resource that requires authentication.
But i'd like to do this in a "clear" way.
thx and best,
Viktor
there has been some discussions on that within the chromium-extensions mailing list:
http://groups.google.com/a/chromium.org/group/chromium-extensions/browse_thread/thread/6e46a3a6e46d9110/
Basically, as a user suggested, you send an Xml Http Request to google.com, and search through regex, if a current user is signed in:
Source: Guillaume Boudreau (on chromium-extensions mailing list)
var currentUser;
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function(data) {
if (xhr.readyState == 4) {
currentUser = null;
if (xhr.status == 200) {
var re = new RegExp(/<b class="?gb4"?>[\s]*([^<]+#[^<]+)<\/b>/i);
var m = re.exec(xhr.responseText);
if (m && m.length == 2) {
currentUser = m[1];
}
}
console.log("Currently logged user (on google.com): " +
currentUser);
}
};
xhr.open('GET', 'https://www.google.com/', false);
xhr.send();
chrome.identity.getAuthToken({interactive: false}, function (token) {
if (!token) {
if (chrome.runtime.lastError.message.match(/not signed in/)) {
console.log("not singed in");
} else {
console.log("singed in");
}
}
});
And don't forget to add "identity" to permissions.