Overriding the function shouldInterceptRequest on Android - nativescript

I am not able to override the WebviewClient function shouldInterceptRequest on Android. Getting no error but the function is not called. What am i missing ?
Documentation for the function shouldInterceptRequest();
http://developer.android.com/reference/android/webkit/WebViewClient.html
if(application.android){
try{
android.webkit.WebViewClient.extend({
shouldInterceptRequest: function(_webView,webResourceRequest){
alert('shouldInterceptRequest is called');
return null;
}
});
}catch(e){
alert(e.message);
}
}

I don't see you set your WebViewClient to your WebView. Try to do something like:
var myWebView = page.getViewById("myWebView");
if (myWebView.android) {
try {
var MyWebViewClient = android.webkit.WebViewClient.extend({
shouldInterceptRequest: function(_webView,webResourceRequest){
alert('shouldInterceptRequest is called');
return null;
}
});
myWebView.android.setWebViewClient(new MyWebViewClient());
} catch(e) {
alert(e.message);
}
}

Related

How can I send a synchronous ajax request to my server in onunload function

I need to send a ajax request to my server before web page close, my send code is below.
SendByAajx = function(msg) {
var response;
var xmlHttpReg;
if(window.XMLHttpRequest){
xmlHttpReg = new XMLHttpRequest();
} else if(window.ActiveXObject) {
xmlHttpReg = new ActiveXObject("Microsoft.XMLHTTP");
} else {
throw new Error("Unsupported borwser");
}
if(xmlHttpReg != null) {
xmlHttpReg.open("get", "https://127.0.0.1:57688/test"+'?'+msg, false);
xmlHttpReg.send(null);
if(xmlHttpReg.readyState==4){
if(xmlHttpReg.status == 200) {
var data = JSON.parse(xmlHttpReg.responseText);
if(typeof(data.errorcode) == "number" &&
data.errorcode != 0) {
throw("response error:" + data.errorcode);
}
response = data.result;
} else {
throw new Error("Error");
}
}
}
return response;
}
When I call this function in a button onclick event, it works.
function GetOnClick() {
try{
var result = SendByAajx (“data”);
} catch (e) {
//alert(errorInfo);
}
SetButtonDisabled(false);
}
But when I call this function when the page is unloaded, it doesn't work.
<body onload="javascript:OnLoad();" onunload="javascript:OnUnLoad()">
function OnUnLoad() {
try{
var result = SendByAajx(“data”);
} catch (e) {
//alert(errorInfo);
}
}
When I debug the application, the JS execution stops after this line:
xmlHttpReg.send(null);
It didn’t go to the next line:
if(xmlHttpReg.readyState==4)
The “data” is also not sent to the server.
What is wrong with my program, can ajax be called in an onunload function? What should I do to make it work?

XmlHttpRequest.responseJSON is not returned on ajaxError function

I'm trying to handle all ajax exceptions globally in my application.
I have a simple validation exception that is thrown after an ajax post request is sent to the server.
if (string.IsNullOrEmpty(name)) { throw new Exception("Name cannot be empty."); }
I have a class the overrides the OnException method:
public override void OnException(ExceptionContext filterContext)
{
if (filterContext.ExceptionHandled || !filterContext.HttpContext.IsCustomErrorEnabled)
{
return;
}
if (filterContext.HttpContext.Request.IsAjaxRequest())
{
filterContext.HttpContext.Response.StatusCode = (int)HttpStatusCode.BadRequest;
filterContext.Result = new JsonResult
{
Data = new { message = filterContext.Exception.Message },
JsonRequestBehavior = JsonRequestBehavior.AllowGet
};
filterContext.ExceptionHandled = true;
filterContext.HttpContext.Response.Clear();
}
else
{
base.OnException(filterContext);
}
}
And a javascript function that listens to all ajax errors:
$(document).ajaxError(function(e, xhr, settings, exception) {
e.stopPropagation();
if (xhr.responseJSON != null) {
showMessage(xhr.responseJSON.message, ERROR);
}
});
The problem is, on my Azure server which is configured for https, the xhr.responseJSON is not returned. However, it works fine locally and I am able to display the exception message thrown. Is https somehow blocking the request? I have tried locally to run my application through https but I'm not able to recreate the issue.
I'm intending to use the same methodology for much more than just validation exceptions, as I know they can be easily handled from the client.
I had the same issue.
Adding filterContext.HttpContext.Response.TrySkipIisCustomErrors = true fixed the issue for me.
So in your case:
public override void OnException(ExceptionContext filterContext)
{
if (filterContext.ExceptionHandled || !filterContext.HttpContext.IsCustomErrorEnabled)
{
return;
}
if (filterContext.HttpContext.Request.IsAjaxRequest())
{
filterContext.HttpContext.Response.StatusCode = (int)HttpStatusCode.BadRequest;
filterContext.Result = new JsonResult
{
Data = new { message = filterContext.Exception.Message },
JsonRequestBehavior = JsonRequestBehavior.AllowGet
};
filterContext.ExceptionHandled = true;
filterContext.HttpContext.Response.Clear();
// Added this line
filterContext.HttpContext.Response.TrySkipIisCustomErrors = true
}
else
{
base.OnException(filterContext);
}
}

Prevent Kendo grid popup edit from closing on Error

I am trying to handle the server error when creating/updating/deleting item from kendo grid. But when a error is thrown, the kendo grid closes no matter what.
function kendo_error_handler(e) {
if (e.errors) {
var message = "Errors:\n";
$.each(e.errors, function (key, value) {
if ('errors' in value) {
$.each(value.errors, function () {
message += this + "\n";
});
}
showErrorMessages(key, message);
});
//this does not work
var grid = this;
gird.one("dataBinding", function (e) {
e.preventDefault();
});
}
}
Does anybody have any other solution? e.preventDefault() doesn't work either.
This worked for me. Just in case anybody needs this.
function kendo_error_handler(gridName) {
return function (e) {
if (e.errors) {
var grid = $('#'+gridName).data("kendoGrid");
grid.one("dataBinding", function (ev) {
ev.preventDefault();
var message = "Errors:\n";
$.each(e.errors, function (key, value) {
if ('errors' in value) {
$.each(value.errors, function () {
message += this + "\n";
});
}
showErrorMessages(key, message);
});
});
}
else {
$("#errorContainer").text("");
}
}
}
is it cause it says " gird.one(" instead of "grid.one("

ASP.NET MVC Ajax Error returning view instead of ajax

I'm making an ASP.NET MVC call to a method via AJAX and the error throws an exception. I'd like the message of the exception to be passed back to the client, and I'd prefer not to have to catch the exception. Something like this:
[HttpPost]
public ActionResult AddUser(User user) {
if (UserIsValid(user)) {
return Json(new { resultText = "Success!" });
}
throw new Exception("The user was invalid. Please fill out the entire form.");
}
I'm seeing in my firebug response an HTML page
<!DOCTYPE html>
<html>
<head>
<title>"The user was invalid. Please fill out the entire form."</title>
.....
I'd like to not be forced to use a try catch block to do this. Is there a way to automatically get the jQuery $(document).ajaxError(function () {} to read in this exception message? Is this bad practice? Can I override the controller OnException? Or do I have to try/catch and return JSON?
Something like this would be nice:
$(document).ajaxError(function (data) {
alert(data.title);
});
You can do this with a custom filter:
$(document).ajaxError(function(event, jqxhr) {
console.log(jqxhr.responseText);
});
-
[HttpPost]
[CustomHandleErrorAttribute]
public JsonResult Foo(bool isTrue)
{
if (isTrue)
{
return Json(new { Foo = "Bar" });
}
throw new HttpException(404, "Oh noes...");
}
public class CustomHandleErrorAttribute : HandleErrorAttribute
{
public override void OnException(ExceptionContext filterContext)
{
var exception = filterContext.Exception;
var statusCode = new HttpException(null, exception).GetHttpCode();
filterContext.Result = new JsonResult
{
JsonRequestBehavior = JsonRequestBehavior.AllowGet, //Not necessary for this example
Data = new
{
error = true,
message = filterContext.Exception.Message
}
};
filterContext.ExceptionHandled = true;
filterContext.HttpContext.Response.Clear();
filterContext.HttpContext.Response.StatusCode = statusCode;
filterContext.HttpContext.Response.TrySkipIisCustomErrors = true;
}
}
Somewhat inspired by this blogpost: http://www.prideparrot.com/blog/archive/2012/5/exception_handling_in_asp_net_mvc
Rather than handle an exception that was raised by the server, why not have a flag in the JSON response?
[HttpPost]
public ActionResult AddUser(User user) {
if (UserIsValid(user)) {
return Json(new { success = true, resultText = "Success!" });
}
return Json(new { success = false, resultText = "The user was invalid. Please fill out the entire form." });
}

Return a JSON result after deleting an item

I'm developing a web application with MVC 3 and want to return a message to the user after he has deleted an item successfully.
MyWallController method looks like this:
[HttpPost]
public ActionResult DeleteAlbum(Guid albumId)
{
try
{
this.albumService.DeleteAlbum(albumId);
return Json(new { success = true, msg = "Album successfully deleted" }, JsonRequestBehavior.AllowGet);
}
catch (FPSException e)
{
return Json(new { success = false, msg = e.Message });
}
catch (Exception)
{
throw new HttpException(500, "Error while deleting album");
}
}
The link:
<a class="open-DeleteAlbumDialog" href="http://localhost:2941/MyWall/DeleteAlbum?albumId=0f49b1ad-8ec1-4fca-b8e2-28bdbf47824e">Delete</a>
The JavaScript:
$(function () {
$(document).on('click', '.open-DeleteAlbumDialog', function () {
var answer = confirm('Are you sure you want to delete this album?')
if (answer) {
$.post(this.href, function (data) {
if (data.success) {
// do something
} else {
// do something else
}
});
}
else return false;
});
However the function defined inside post is never called and what I get is a "the resource cannot be found". But the item has been deleted successfully.
All kinds of help is appreciated.
Your link is still working. You need to preventDefault:
$(function () {
$(document).on('click', '.open-DeleteAlbumDialog', function (e) {
e.preventDefault();
var answer = confirm('Are you sure you want to delete this album?')
if (answer) {
$.post(this.href, function (data) {
if (data.success) {
// do something
} else {
// do something else
}
});
}
});

Resources