Issue
Does anybody know if I can change the responseText
of the ajax object so that I can make a bottleneck to all messages that uses ajax request and change them before the responseText
is used anywhere the request come from?
I saw that responseText
has only the getter property so Firefox don’t let me change it, but I want that all income messages from my website goes through this new object and change it.
Hope anyone can help me.
Solution
Assuming you have no control over the page being called…
The ResponseText is purposely read-only (for various reasons). Of course, you can certainly insert an intermediary JavaScript function inside any of the following events: OnSuccess, OnError and OnComplete. This function could alter your data and respond differently based on your criteria.
UPDATE:
As promised, below is controller-class I use for one of my applications. Notice the ExceptionManager contained in the USAGE area holds a copy of the PeepingTom.Controller. Also notice the ExceptionManager is passed-into the controller (as context)…and as such…it intercepts all calls.
Of course, your classes could do a parred-down version of this. If you want ALL you classes to use the same controller (rather than have their own instance)…you certainly could do that.
<script type="text/javascript">
var PeepingTom = (function($) {
var publicInstances = {};
// ***********************
// Controller
publicInstances.Controller = Controller;
function Controller(context, processorUrl, controllerUrl) {
// ********** PROPERTIES: **********
var Self = this;
/// <summary>Represents the context-class using this instance.</summary>
this.Context = context;
/// <summary>Represents a handle returned from a setTimeout or setInterval call which can be used to cancel the timer.</summary>
this.TimerHandle;
/// <summary>Represents a wait timer until the next long-poll is executed.</summary>
this.WaitInterval = 1000;
/// <summary>Represents a relative path to the long-poll Processor.</summary>
this.LongPollingProcessor = processorUrl;
/// <summary>Represents a relative path to the long-poll Controller.</summary>
this.LongPollingController = controllerUrl;
// ********** METHODS **********
/// <!-- Initialization -->
/// <summary>Initializes the (overall) component.</summary>
this.Initialize = function() {
if (Self.Context.GetRequestObject)
Self.SetupAjax();
else
alert("Context must implement 'GetRequestObject()'.");
}
/// <!-- Communication -->
/// <summary>Setup default values for ALL ajax requests</summary>
/// <see cref="http://api.jquery.com/jQuery.ajaxSetup/"></see>
this.SetupAjax = function() {
$.ajaxSetup({
cache: false,
type: 'POST'
});
}
/// <!-- Communication -->
/// <summary>Makes an ajax call to the long-poll Listener.</summary>
this.Fetch = function() {
$.ajax({
complete: Self.OnComplete,
data: Self.Context.GetRequestObject(),
dataType: 'json',
error: Self.OnError,
success: Self.OnSuccess,
url: Self.LongPollingProcessor
});
}
/// <summary>Logs a message to the console.</summary>
this.Log = function(message) {
if (console)
console.log(message);
}
// ********** EVENTS **********
/// <!-- Communication -->
/// <summary>A function called when the request finishes.</summary>
/// <see cref="http://api.jquery.com/jQuery.ajax/"></see>
/// <param name="xmlHttpRequest">The XMLHttpRequest object.</param>
/// <param name="status">A string containing the success or error code.</param>
this.OnComplete = function(xmlHttpRequest, status) {
if (Self.Context.OnComplete)
Self.Context.OnComplete(xmlHttpRequest, status);
}
/// <!-- Communication -->
/// <summary>Setup default values for ALL ajax requests</summary>
/// <see cref="http://api.jquery.com/jQuery.ajax/"></see>
/// <param name="xmlHttpRequest">The XMLHttpRequest itself (object).</param>
/// <param name="status">A string describing the type of error that occurred</param>
/// <param name="error">The exception object (optional).</param>
this.OnError = function(xmlHttpRequest, status, error) {
if (Self.Context.OnError)
Self.Context.OnError(xmlHttpRequest, status, error);
Self.Log("OnError - " + error);
}
/// <!-- Communication -->
/// <summary>(optional) Actions to take when the session becomes invalid.</summary>
/// <see>OnSuccess: data.SessionValid = false</see>
this.OnSessionExpired = function(data) {
if (Self.Context.OnSessionExpired)
Self.Context.OnSessionExpired(data);
if (data) {
if (data.Exception) {
Self.Log("InnerException - OnError: " + data.Exception.InnerException);
Self.Log("Message - OnError: " + data.Exception.Message);
Self.Log("Source - OnError: " + data.Exception.Source);
Self.Log("StackTrace - OnError: " + data.Exception.StackTrace);
}
}
}
/// <!-- Communication -->
/// <summary>A function to be called if the request succeeds.</summary>
/// <see cref="http://api.jquery.com/jQuery.ajax/"></see>
/// <param name="data">The data returned from the server (formatted according to the 'dataType' parameter).</param>
/// <param name="status">A string describing the status.</param>
/// <param name="xmlHttpRequest">The XMLHttpRequest object (available as of jQuery 1.4).</param>
this.OnSuccess = function(data, status, xmlHttpRequest) {
if (data == null) {
Self.OnSessionExpired(data);
}
else {
if (!data.SessionValid) {
Self.OnSessionExpired(data);
}
else {
if (Self.Context.OnSuccess)
Self.Context.OnSuccess(data, status, xmlHttpRequest);
}
}
}
}
// ***********************
// Utility
publicInstances.Utility = Utility;
function Utility() {
// ********** PROPERTIES: **********
var Self = this;
// ********** METHODS **********
/// <summary>Creates a new GUID</summary>
/// <remarks>This operational method is useful in creating unique Id's.</remarks>
this.CreateGuid = function() {
var result, i, j;
result = '';
for (j = 0; j < 32; j++) {
if (j == 8 || j == 12 || j == 16 || j == 20)
result = result + '-';
i = Math.floor(Math.random() * 16).toString(16).toUpperCase();
result = result + i;
}
return result;
}
/// <summary>Converts a milli-second formatted-date into a normalized date format.</summary>
this.ConvertDateFromMilliSeconds = function(text) {
var match;
if (!(match = text.match(/\d+/)))
return "";
var date = new Date();
date.setTime(match[0] - 0);
return date;
}
/// <summary>Converts a date to UTC time.</summary>
this.ConvertUTCtoLocalTimeZone = function(date) {
// creates a Date in local time
var realDate = new Date(parseInt(date.substr(6)));
// converts the Date to UTC by adding or subtracting the time zone offset
var offsetMilliseconds = realDate.getTimezoneOffset() * 60 * 1000;
realDate.setTime(realDate.getTime() - offsetMilliseconds);
date = realDate.toLocaleString();
return date;
}
/// <summary>Converts a UTC date to a short-date (mm/dd/yyyy).</summary>
this.ConvertUTCtoShortDate = function(utcDate) {
var month = utcDate.getUTCMonth();
var day = utcDate.getUTCDay();
var year = utcDate.getUTCFullYear();
return month + "/" + day + "/" + year;
}
// ********** EVENTS **********
}
return publicInstances;
})(jQuery);
</script>
USAGE:
Here is a copy of an Exception Manager that uses the Controller (above)
<script type="text/javascript">
var ExceptionManager = (function($) {
var publicInstances = {};
// ***********************
// Observer
publicInstances.Observer = Observer;
function Observer(userControlId, asOf) {
// ********** PROPERTIES **********
var Self = this;
/// <summary>Controls long-polling communications.</summary>
this.Controller = null;
/// <summary>Represents a utility class-instance.</summary>
this.Utility = null;
/// <summary>Represents the Viewer object.</summary>
this.Viewer = null;
/// <summary>The TEMPLATE ID used in creating an observation.</summary>
this.TemplateId = "#template-exceptionManager-Exception";
/// <summary>Represents a collection of observation objects.</summary>
this.Observations = null;
/// <summary>Used to pause processing of observations.</summary>
this.Pause = false;
/// <summary>Alters the speed with which observations are processed.</summary>
this.PauseInterval = 2000;
/// <summary>Determines how long to wait until the next long-poll is executed.</summary>
this.WaitInterval = 2000;
/// <summary>The design-time Id of this user-control instance.</summary>
this.UserControlId = userControlId;
/// <summary>The datetime stamp used in determining which observations to gather-up.</summary>
this.AsOf = asOf;
/// <summary>The ID of the last observation in the current batch.</summary>
this.LastId = 0;
/// <summary>The relative path of the long-polling processor.</summary>
this.ProcessorUrl = '<%=ResolveUrl("~/Handlers/ActivityExceptionProcessor.ashx")%>';
/// <summary>The relative path of the long-polling controller.</summary>
this.ControllerUrl = '<%=ResolveUrl("~/Handlers/ActivityExceptionController.ashx")%>';
// ********** METHODS **********
/// <!-- Initialization -->
/// <summary>Initializes the Observer.</summary>
this.Initialize = function() {
// Find the activityViewer within the document (the object that manages the display-queue)
if ((activityViewer != null) && (activityViewer.IsInitialized)) {
Self.Controller = new PeepingTom.Controller(Self, Self.ProcessorUrl, Self.ControllerUrl);
Self.Controller.WaitInterval = Self.WaitInterval;
Self.Utility = new PeepingTom.Utility();
Self.Observations = new Array; // THIS objects queue of observations.
Self.Viewer = activityViewer;
Self.InitializeQueue(); // THIS objects queue of observations.
Self.Controller.Fetch();
}
else
setTimeout(Self.Initialize, 2000); // Every 2 seconds
}
/// <!-- Initialization -->
/// <summary>Initializes the queue that processes Observations.</summary>
this.InitializeQueue = function() {
if (!Self.Pause) {
if (Self.Observations.length > 0) {
var observation = Self.Observations.pop();
Self.AppendObservation(observation);
}
setTimeout(Self.InitializeQueue, Self.PauseInterval);
}
}
/// <summary>Enqueue's this observer's newly found Observations.</summary>
this.Enqueue = function(observations) {
if ($(observations).length > 0) {
var lastItem = $(observations).last();
Self.LastId = lastItem[0].Id;
$(observations).each(function() {
// Append dynamic properties
this.TemplateId = Self.TemplateId;
// Append dynamic events
this.OnProcessed = function() { Self.OnProcessed(this); };
Self.Viewer.Enqueue(this);
});
}
}
/// <summary>Returns a populated XMLHttpRequest object.</summary>
this.GetRequestObject = function() {
var request = { UserControlId: Self.UserControlId, AsOf: Self.AsOf };
return request;
}
// ********** EVENTS **********
/// <!-- Notification -->
/// <summary>Notifies this control when an observation is processed.</summary>
this.OnProcessed = function(observation) {
if (observation.Id == Self.LastId) {
Self.Controller.TimerHandle = setTimeout(function() { Self.Controller.Fetch(); }, Self.WaitInterval);
}
}
/// <!-- Communication -->
/// <summary>A function called when the request finishes.</summary>
/// <see cref="http://api.jquery.com/jQuery.ajax/"></see>
/// <param name="xmlHttpRequest">The XMLHttpRequest object.</param>
/// <param name="status">A string containing the success or error code.</param>
this.OnComplete = function(xmlHttpRequest, status) {
}
/// <!-- Communication -->
/// <summary>Setup default values for ALL ajax requests</summary>
/// <see cref="http://api.jquery.com/jQuery.ajax/"></see>
/// <param name="xmlHttpRequest">The XMLHttpRequest itself (object).</param>
/// <param name="status">A string describing the type of error that occurred</param>
/// <param name="error">The exception object (optional).</param>
this.OnError = function(xmlHttpRequest, status, error) {
Self.Controller.Log("ExceptionManager - OnError: " + error);
alert("ExceptionManager - OnError");
}
/// <!-- Communication -->
/// <summary>(optional) Actions to take when the session becomes invalid.</summary>
/// <see>OnSuccess: data.SessionValid = false</see>
this.OnSessionExpired = function(data) {
Self.Controller.Log("ExceptionManager - OnSessionExpired");
alert("ExceptionManager - OnSessionExpired");
}
/// <!-- Communication -->
/// <summary>A function to be called if the request succeeds.</summary>
/// <see cref="http://api.jquery.com/jQuery.ajax/"></see>
/// <param name="data">The data returned from the server (formatted according to the 'dataType' parameter).</param>
/// <param name="status">A string describing the status.</param>
/// <param name="xmlHttpRequest">The XMLHttpRequest object (available as of jQuery 1.4).</param>
this.OnSuccess = function(data, status, xmlHttpRequest) {
Self.AsOf = data.AsOf;
if (data.Observations) {
if (data.Observations.length > 0)
Self.Enqueue(data.Observations);
else
Self.Controller.TimerHandle = setTimeout(function() { Self.Controller.Fetch(); }, Self.WaitInterval);
}
}
}
return publicInstances;
})(jQuery);
</script>
Answered By – Prisoner ZERO
This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0