Cross domain call not working in FireFox and Chrome - asp.net

I am making a asynchronous request to different server for some data using jquery. It works fine in IE, but doesn't work in FireFox and Chrome, when it reaches the code where the request to other server is made, it freezes there and a blank page is shown. If I remove that piece of code, the ajax works fine.
Also, when I place a breakpoint at document.ready, the breakpoint is hit when debugging using IE, but it's not hit when debugging using FireFox.
Following is the JQuery I am using
jQuery(document).ready(function ($) {
$('.tabs a, .tabs span').livequery('click', function () {
var currentTab = $(this).parents('li:first');
if (!currentTab.is('.active')) {
var currentContent = $('.tab_container .' + currentTab.attr('class'));
$('.tabs li').removeClass("active");
currentTab.addClass("active");
var url = $(this).attr("href");
var newContent = "";
if (currentContent.length == 0) {
$.get(url, {}, function (result) {
$('#tabs.tab_container div:visible').fadeOut(100, function () {
$('#tabs.tab_container')
.html(result)
.fadeIn(100);
});
}, 'html');
}
else {
$('#tabs.tab_container div:visible').fadeOut(100, function () {
currentContent.fadeIn(100);
});
}
}
return false;
});
});
Any help will be highly appreciated.

According to the docs for jQuery.Get:
Due to browser security restrictions, most "Ajax" requests are subject to the same origin policy; the request can not successfully retrieve data from a different domain, subdomain, or protocol.
If you're after JSON responses, then you should consider using the JSONP option that has been rolled into the GetJSON method.
There are a couple of people out there who have however provided some workarounds for the Get limitation:
The jQuery Cross Domain Ajax Guide
Cross Domain Requests with jQuery

Related

Branch Deep Linking not working in Google Analytics hitCallback

I'm using both Google Analytics and branch.io in this website.
The website is designed for mobile.
The problem is that when clicking the banner with text "OPEN", the app cannot be opened.
Here is the code for the click:
$scope.openApp = () => {
let appOpened = false;
const open = () => {
if (!appOpened) {
appOpened = true;
branch.deepviewCta();
}
};
$timeout(open, 1000);
ga('send', 'event', 'homepage', 'download', {
hitCallback() {
open();
}
});
};
If I get rid of the GA code, it works fine:
$scope.openApp = () => {
let appOpened = false;
const open = () => {
if (!appOpened) {
appOpened = true;
branch.deepviewCta();
}
};
$timeout(open, 1000);
open();
};
The reason I put open() in hitCallback is to make sure GA sends out the hit because open() will redirect to another page.
Can you help me?
Alex from Branch.io here:
The Branch deepviewCta() function works on iOS 9+ by triggering an automatic redirect to a Universal Link URL (which opens the app) and then going to a fallback URL if that fails. But Apple is very specific about the situations in which a Universal Link is allowed to launch the app (including things like how long of a pause is allowed before redirection). Of course these restrictions are not public, so all we can do is guess. My suspicion is that putting the deepviewCta() function inside a GA callback is falling outside of Apple’s rules, so the app never opens and you are instead being sent to the fallback URL.
I can think of two options here:
You can build some way to trigger the GA and Branch functions separately so that they don’t conflict with Apple’s requirements.
We actually have a brand new, one-click integration with Google Analytics, which you can read about here and here. If you set that up, you’ll get all Branch-related events automatically instead of needing to manually collect link click data.
Hopefully that helps!

Why do Google's JS Client SDK function callbacks fail?

I'm currently in the learning phase for how the Google JS Client SDK works, since my boss needs me to learn how to integrate a Sign In button to his site to enable people to Authenticate via Google. I am testing the code for the custom Sign In button, with a touch of added functionality (like a Sign Out button), and in the process I've practically copy/pasted the code from their website. Let me show you the code first and then explain the issue, so that you can understand where the code is failing:
<script src="https://apis.google.com/js/client.js?onload=init"></script>
<script type="text/javascript">
var clientId = '{my client id here}'; // for web
var apiKey = '{my api key here}';
var scopes = 'profile email';
function SignOut() {
// I know, sloppy, but the signOut method from Google doesn't work.
window.location = 'https://accounts.google.com/logout';
// Additional code if necessary.
};
function makeApiCall() {
gapi.client.load('plus', 'v1', function () {
var request = gapi.client.plus.people.get({ 'userId': 'me' });
request.execute(function (response) {
var heading = document.createElement('h4');
var image = document.createElement('img');
image.src = response.image.url;
heading.appendChild(image);
heading.appendChild(document.createTextNode(response.displayName));
document.getElementById('name').appendChild(heading);
alert('User logged in. makeApiCall() has executed.');
})
})
};
function init() {
gapi.client.setApiKey(this.apiKey);
window.setTimeout(checkAuth, 1);
console.log('Up and ready to go.');
};
function checkAuth() {
// Triggers when the page and the SDK loads.
gapi.auth.authorize({ client_id: clientId, scope: scopes, immediate: true }, handleAuthResult);
};
function handleAuthClick(event) {
// Triggers after a user click event to ensure no popup blockers interfere.
gapi.auth.authorize({ client_id: clientId, scope: scopes, immediate: false }, handleAuthResult);
return false;
};
function handleAuthResult(authResult) {
var authorizeButton = document.getElementById('SignInBtn');
var signoutButton = document.getElementById('SignOutBtn');
if (authResult && !authResult.error) {
var V = JSON.stringify(authResult);
localStorage.setItem('GoogleAuthResult', V);
console.log(V); // Just for testing...
var authTimeout = (authResult.expires_in - 5 * 60) * 1000; setTimeout(checkAuth, authTimeout); // As recommended by a Google employee in a video, so that the token refreshes.
authorizeButton.style.display = 'none'; // Switching between Sign In and Out buttons.
signoutButton.style.display = 'inline-block';
makeApiCall();
} else {
// Immediate:true failed so user is NOT signed in.
// Make the Sign In button the one visible and prep it
// so that it executes the Immediate:false after user click:
authorizeButton.style.visibility = 'inline-block';
authorizeButton.onclick = handleAuthClick;
signoutButton.style.visibility = 'none';
}
};
</script>
The handleAuthClick function does run on the button click, but after taking the user to the Google Sign In page, when that page brings me back, the browser kinda flickers and the handleAuthResult function does not execute. Therefore, nothing changes in the page after the successful sign in; the button displayed is the Sign In button (Sign Out button not visible) and no information is displayed on the 'name' textNode. This happens on Internet Explorer (11), Firefox (39) and Chrome (44). Also, it happens at home on my laptop (straight connection to the web via Cable broadband) and at work (on Windows 8.1 behind an Active Directory).
I began wondering so I started refreshing the browser page and after a couple of refreshes, since the script runs from the beginning, the immediate:true fires again and voilá: user is connected and API call triggers.
So, on my laptop, I changed the function being called back, in the immediate:false line's callback parameter, to the init() function and that fixed the problem: everything runs smoothly from beginning to end. Yet, this is not the way it is supposed to work. I still don't know what is going on with that line.
This morning, on my computer at work (behind Active Directory), that fix didn't work. I have to refresh the page a couple of times so that the script runs from the beginning and the immediate:true triggers recognizing the user's Signed In state and displaying the proper button on screen.
Any ideas on why does this callback fail?
You need to define your apiKey in the first section of your code
var clientId = '{my client id here}'; // for web
var apiKey = '{my api key here}'
Maybe thats the problem.
Google ApiKeys

ASP.NET Route config for Backbone Routes with PushState

I have run into an issue recently where we have been told to remove the hash symbols from our Backbone applications. This presents two problems: (a) the ASP.NET routes need to handle any remotely linked URL (currently this is no problem with the hash symbols) so that we're not hitting a 404 error and (b) the proper route needs to be preserved and passed on to the client side (Backbone) application. We're currently using ASP.NET MVC5 and Web API 2 for our backend.
The setup
For an example (and test project), I've created a test project with Backbone - a simple C# ASP.NET MVC5 Web Application. It is pretty simple (here is a copy of the index.cshtml file, please ignore what is commented out as they'll be explained next):
<script type="text/javascript">
$(document).ready(function(event) {
Backbone.history.start({
//pushState: true,
//root: "/Home/Index/"
});
var Route = Backbone.Router.extend({
routes: {
"test/:id": function (event) {
$(".row").html("Hello, " + event);
},
"help": function () {
alert("help!");
}
}
});
var appRouter = new Route();
//appRouter.navigate("/test/sometext", { trigger: true });
//appRouter.navigate("/help", { trigger: true });
});
</script>
<div class="jumbotron">
<h3>Backbone PushState Test</h3>
</div>
<div class="row"></div>
Now, without pushState enabled I have no issue remote linking to this route, ie http://localhost/Home/Index#test/sometext
The result of which is that the div with a class of .row is now "Hello, sometext".
The problem
Enabling pushState will allow us to replace that pesky # in the URL with a /, ie: http://localhost/Home/Index/test/sometext. We can use the Backbone method of router.navigate("url", true); (as well as other methods) to use adjust the URL manually. However, this does not solve the problem of remote linking. So, when trying to access http://localhost/Home/Index/test/sample you just end up with the typical 404.0 error served by IIS. so, I assume that it is handled in in the RouteConfig.cs file - inside, I add a "CatchAll" route:
routes.MapRoute(
name: "CatchAll",
url: "{*clientRoute}",
defaults: new { controller = "Home", action = "Index" }
);
I also uncomment out the pushState and root attributes in the Backbone.history.start(); method:
Backbone.history.start({
pushState: true,
root: "/Home/Index/"
});
var Route = Backbone.Router.extend({
routes: {
"test/:id": function (event) {
$(".row").html("Hello, " + event);
},
"help": function () {
alert("help!");
}
}
});
var appRouter = new Route();
//appRouter.navigate("/test/sometext", { trigger: true });
//appRouter.navigate("/help", { trigger: true });
This allows me to at least let get past the 404.0 page when linking to these routes - which is good. However, none of the routes actually "trigger" when I head to them. After attempting to debug them in Chrome, Firefox, and IE11 I notice that none of the events fire. However, if I manually navigate to them using appRouter.navigate("/help", { trigger: true }); the routes are caught and events fired.
I'm at a loss at this point as to where I should start troubleshooting next. I've placed my Javascript inside of the $(document).ready() event as well as the window.onload event also (as well as not inside of an event); none of these correct the issue. Can anyone offer advice on where to look next?
You simply have to move Backbone.history.start after the "new Route" line.
var Route = Backbone.Router.extend({
routes: {
"test/:id": function (event) {
$(".row").html("Hello, " + event);
},
"help": function () {
alert("help!");
}
}
});
var appRouter = new Route();
Backbone.history.start({
pushState: true,
root: "/Home/Index/"
});
Make sure you go to ".../Home/Index/help". If it doesn't work, try temporarily removing the root and go to ".../help" to see if the root is the problem.
If you still have troubles, set a js breakpoint in Backbone.History.loadUrl on the "return" line. It is called from the final line of History.start to execute the current browser url on page load. "this.matchRoot()" must pass then, "fragment" is matched against each "route" or regexp string in "this.handlers". You can see why or why not the browser url matches the route regexps.
To set to the js breakpoint, press F12 in the browser to open the dev console, press Ctrl-O or Ctrl-P to open a js file, then type the name of the backbone js file. Then search for "loadUrl:". You can also search for "Router =" to find the start of the router class definition (same as for "View =" and "Model =" to find the backbone view/model implementation code). I find it quite useful to look at the backbone code when I have a question like this. It is surprisingly readable and what better place to get answers?
If your js files happen to be minified/compressed, preferably turn this off. Alternately you can try the browser unminify option. In Chrome this is the "{}" button or "pretty print". Then the js code is not all on 1 line and you can set breakpoints. But the function and variable names may still be mangled.
I have solved my own problem using what feels to be "hackish", via the following. If anyone can submit a better response it would be appreciated!
My Solution:
I globally override the default Backbone.Router.intilaize method (it is empty) with the following:
$(document).ready(function (event) {
var _root = "/Home/Index/";
_.extend(Backbone.Router.prototype, {
initialize: function () {
/* check for route & navigate to it */
var pathName = window.location.pathname;
var route = pathName.split(_root)[1];
if (route != undefined && route != "") {
route = "/" + route;
this.navigate("", { trigger: false });
this.navigate(route, { trigger: true });
}
}
});
});

How to test Meteor router or Iron router with laika

I'm using laika for testing and the meteor-router package for routing. I want to do tests that navigate to some page, fill a form, submit it and check for a success message, but I'm stuck on the navigation part. This was my first attempt:
var assert = require('assert');
suite('Router', function() {
test('navigate', function(done, server, client) {
client.eval(function() {
Meteor.Router.to('test');
var title = $('h1').text();
emit('title', title);
})
.once('title', function(title) {
assert.equal(title, 'Test');
done();
});
});
});
This doesn't work because Meteor.Router.to doesn't have a callback and I don't know how to execute the next line when the new page is loaded.
I tried also with something like this
var page = require('webpage').create();
page.open('http://localhost:3000/test', function () {
...
}
but I got the error Error: Cannot find module 'webpage'
Edit
I'm moving to iron router, so any answer with that also will be helpful.
I had the same problem. I needed to navigate to some page before running my tests. I'm using iron router as well. I figured you can't just execute Router.go('foo') and that's it. You need to wait until the actual routing took place. Fortunately the router exposes a method Router.current() which is a reactive data source that will change as soon as your page is ready. So, in order to navigate to a specific route before running my tests, I firstly run the following code block:
// route to /some/path
client.evalSync(function() {
// react on route change
Deps.autorun(function() {
if (Router.current().path == '/some/path') {
emit('return');
this.stop();
}
});
Router.go('/some/path');
});
Since this is within an evalSync()everything that follows this block will be executed after the routing has finished.
Hope this helps.
Laika now includes a waitForDOM() function you can set up to wait for a specific DOM element to appear, which in this case would be an element in the page you're loading.
client.eval(function() {
Router.go( 'test' );
waitForDOM( 'h1', function() {
var title = $('h1').text();
emit( 'title', title );
});
});
The first parameter is a jQuery selector.

Does IE8 have any specific restrictions on postMessage to IFrames?

I have a web application with an iframe that needs to communicate with its hosting page. The iframe and the host are on different domains and protocols (the iframe is https, the main page http). I use postMessage to get a small bit of state (user tracking) from the outer page into the iframe.
When the iframe is loaded, it sends a short message out to the top page to ask for the visitorid:
if ($.w.top != $.w) $.f.postMessage($.w.top, 'Get visitorId');
($.f.postMessage(w, m) is just a wrapper around postMessage, that does nothing if typeof w.postMessage === 'undefined'). On the outer page, we have a message listener:
// Set up event listener so that we can respond when any iframes
// inside of us ask for our visitorId
$.f.listen($.w, 'message', giveVisitorId);
function giveVisitorId(event) {
$.w['zzzzz'] = event.source;
if (event.data === 'Get visitorId') {
alert('about to reply from '+window.location.href+' with visitorid, typeof event.source.postMessage is ' + typeof(event.source.postMessage));
event.source.postMessage('visitorId=' + $.v.visitorId, '*');
}
}
The inner frame has a listener registered for the response:
$.f.listen($.w, 'message', receiveVisitorId);
function receiveVisitorId(event) {
alert('receiveVisitorId called with: ' + event.data + ' in window '+window.location.href);
var s = event.data.split('=');
if (s[0] === 'visitorId' && s.length === 2) {
$.v.visitorId = s[1];
$.w.clearTimeout(giveUp);
rest();
}
}
This all works as it is supposed to on chrome and firefox on OSX (when the iframe is loaded we get two alerts, one from receiveVisitorId and one from giveVisitorId); however on IE8 on XP we only get the first alert (from giveVisitorId).
This is strange enough, since it seems that the postMessage going out works and the one going in doesn't; what's truly perplexing is that if we go to the console and run zzzzz.postMessage('hi', '*') the alert in receiveVisitorId happens just as expected! (Note that we saved event.source in window.zzzzz).
Does anyone have an idea why this might be happening?
PS: The definitions of $.w.listen and $.w.postMessage, for reference:
listen: function (el, ev, fn) {
if (typeof $.w.addEventListener !== 'undefined') {
el.addEventListener(ev, fn, false);
}
else if (typeof $.w.attachEvent !== 'undefined') {
el.attachEvent('on' + ev, fn);
}
},
postMessage: function(w, m) {
if (typeof w.postMessage !== 'undefined') {
w.postMessage(m, "*");
}
},
We resolved it. The problem was that we were calling $.f.listen after $.f.postMessage in the inner iframe; so when the outer window posted a message to the inner, the listener had not yet been attached. I don't know why this happened in IE and not chrome or firefox, but we just put it down to timing differences between the browsers.

Resources