javascript search for the url in default browser cache - javascript

Please, write me a JavaScript function that search the Browser Cache:
function isInBrowserCache(url)
url: address of a site with JSON response
return: true or false

One possible code that I found and improved is:
var isInBrowserCache = function(url){
window.caches.open('window-cache-v1').then(function(cache) {
cache.match(url, {
ignoreSearch: true,
ignoreMethod: true,
ignoreVary: true
}).then(function(response) {
if (response) {
return true;
} else {
return false;
}
});
});
}
This function always returns false, without the url in Browser Cache and with it.
Maybe the Browser Cache identification string is not "window-cache-v1".
Then there is a new JS cache. If you know the correct string, please write.

WORKS FOR IMAGE URL
Function that checks if an URL of an image is in Browser Cache
#parameter: img_url (URL of an image file)
#return: boolean (true/false)
function isInBrowserCache(img_url) {
var imgEle = document.createElement("img");
imgEle.src = img_url;
return imgEle.complete || (imgEle.width+imgEle.height) > 0;
}
DOES NOT WORK FOR JSON URL
Function that checks if an URL of a JSON source is in Browser Cache
#parameter: json_url (URL of a JSON file)
#return: boolean (true/false)
function isInBrowserCache(json_url) {
var jsonEle = document.createElement("json");
jsonEle.src = json_url;
return jsonEle.complete;
}
The code above is created using the function
is_cached(img_url):boolean
from
how to check if an image was cached in js?

Related

How to clear JSON Object after Ajax

In my ASP.NET Core web application, one of my pages has a sequence of steps that it performs to call stored procedures. Depending on whether or not stored procedures return rows, I route to one of two controller actions (either rendering a partial including an additional input, or overriding what that input would do and just coming back to the page on the next step).
Right now I've got code that is nearly there. My controller actions navigate and process correctly and my Ajax works... Sort of.
Button in the Razor view that calls the Ajax function
<input type="button" value="Run Check" onclick="runCheck('#actionItem.StepID', '#Model.Client.DatabaseConnectionString', '#Model.Client.ClientID')" />
Ajax
<script type="text/javascript">
function runCheck(x, y, z) {
$.ajax({
url: '#Url.Action("ProcessFeedbackHasRows", "Client")',
type: 'POST',
data: { stepId: x, databaseConnectionString: y, clientId: z },
success: function (result) {
if (result) {
alert('true');
var stepId = x;
var databaseConnectionString = y;
var clientId = z;
var url = '#Url.Action("ViewProcessingFeedBackPartial", "Client")';
$("#processingFeedbackPartialDiv").load(url, { stepId, databaseConnectionString, clientId },
function () {
$("#confirmButton").removeAttr("style");
});
} else {
alert('false');
var newUrl = '#Url.Action("Processing", "Client")';
window.location = newUrl;
}
}
});
};
</script>
Controller Action
public JsonResult ProcessFeedbackHasRows(int StepId, string DatabaseConnectionString, int ClientID)
{
bool hasRows = true;
FeedbackDetails feedbackDetails = new FeedbackDetails();
feedbackDetails.Data = _clientProcessingService.GetProcessingFeedbackDetails(StepId, DatabaseConnectionString);
if (feedbackDetails.Data.Rows.Count == 0)
{
_clientProcessingService.RunProcessStepConfirmation(DatabaseConnectionString, StepId, ClientID, "No information returned, automatically proceeding to next step.");
hasRows = false;
}
return new JsonResult (new { HasRows = hasRows });
}
The alerts are there to just prove that the right condition was in fact met and that the right things are happening. And this is where my problems lie. When I had the Network traffic tab of the F12 tools open, I noticed that whatever json object is created first determines all future runs of the code.
For example: let's say I forced the first item to come through with at least 1 row returned, I'd see the alert true, see the JSON object in the Network tab contain true and see my partial view, as expected.
The next several steps would produce a a false result because no rows were returned from the SP in the controller. The bool in the controller would be set to false, the JSON object in the Network tab would say HasRows = false, but my alert would show true and the partial still renders asking me for confirmation. So despite not returning any rows and producing a false result, I see the alert true and the partial is rendered even though in my Network tab I see
The opposite is true as well. If I had the first item through create an object where HasRows = false, and the next several would have been true, subsequent steps return true in the Network tab, but alert false and go through the false logic in the Ajax.
What is the best way to handle this? Is there a way to clear the JSON or something? I figured by creating a new JsonResult at the end of every method call, it would produce a new result to inspect, but it seems to continue using the first one sent in despite being able to see the others in the Network tab.
What I've tried
Disabling cache in Ajax by adding cache: false, right above the URL in the $.ajax setup.
Resetting the json object within the function after my else braces
result = []; and delete result.hasRows;
Despite these attempts, the ajax will always alert and go through whatever logic flow was sent first while the actual object contains the correct variable.
I actually solved this because in my inexperience with javascript and jQuery, I didn't understand exactly how the logic was being handled since I can't very easily debug the javascript the way I can the C#.
Through trial and error and alerts, I found that essentially, the in my Ajax I had to change the if condition to inspect result.hasRows rather than just the result.
<script type="text/javascript">
function runCheck(x, y, z) {
$.ajax({
cache: false,
url: '#Url.Action("ProcessFeedbackHasRows", "Client")',
type: 'POST',
data: { stepId: x, databaseConnectionString: y, clientId: z },
success: function (result) {
if (result.hasRows) {
alert('result = true');
alert('result.hasRows = ' + result.hasRows);
var stepId = x;
var databaseConnectionString = y;
var clientId = z;
var url = '#Url.Action("ViewProcessingFeedBackPartial", "Client")';
$("#processingFeedbackPartialDiv").load(url, { stepId, databaseConnectionString, clientId },
function () {
$("#confirmButton").removeAttr("style");
});
} else {
alert('result = false');
alert('result.hasRows = ' + result.hasRows);
var newUrl = '#Url.Action("Processing", "Client")';
window.location = newUrl;
}
}
});
};
</script>
The initial question still stands though. Assuming I wanted to delete the entire JSON object and use my initial logic present in the question, how can I clear or delete the entire object so that every time I hit that Ajax call, a new object would be inspected? Or is that now how this works and I solved the problem correctly?

Nativescript - uploading images using http module

I'm using "nativescript-imagepicker" plugin to get an image from device library.
To do this, i'm calling this two modules:
var imagepicker = require("nativescript-imagepicker");
var imageSourceModule = require("tns-core-modules/image-source");
For now i have some function that shows the gallery, and i can select an image, that next is converted to base64 string and assigned as global variable for later use:
model.gallery = function () {
var img;
var context = imagepicker.create({mode: "single"});
context.authorize()
.then(function () {
return context.present();
})
.then(function (selection) {
selection.forEach(function (selected) {
img = selected;
model.set('avatar', img);
});
var source = new imageSourceModule.ImageSource();
source.fromAsset(img)
.then(function (imageSource) {
var convertedAvatar = imageSource.toBase64String("jpeg",1);
global.convertedAvatar = convertedAvatar;
});
}).catch(function (e) {
alert ('Error, please try again');
});
};
Everything seems to work fine, but please take a look at image quality (1).
I've tried quality of 90, but seems that string was so long that this http call was crashing an app:
model.test = function() {
var base64 = global.convertedAvatar;
var content = 'type=profile&file='+base64+'&extension=jpeg';
http.request({
url: global.host + 'profile/upload',
method: 'POST',
headers: {"Content-Type": global.cType},
content: content,
}).then(function (response) {
global.loaderHide();
result = response.content.toJSON();
if (response.statusCode == 200) {
success('Success','Data saved.')
} else {
global.alerts('Error',result.message);
}
}).catch(function (error) {
global.alerts('Error', error);
});
};
My question is : i think that my approach is wrong as i have issues. Base64 string is very long. Is there a way to do this right ?
Am i able to maybe resize image so string can be smaller ?
Or maybe this is API's issue (not accepting very long strings)?
Finally, maybe i need to use another method like background http module for uploading images, not base64 strings ?
Thank you for any ideas.
Below attached image, how long base64 string is even with quality set to 1.

How To Open URL In New Tab Using Ajax Success?

Here i am trying to open the file in new tab by calling ViewFile action of Doctor controller using Ajax Success which is in functionabc(this) on click of anchor tag.
Now the problem is that everything is as required but the url doesnot open in new tab.
Below is my Ajax
<script>
function abc(thisEvent) {
debugger;
var getDoCredId = $(thisEvent).attr('docCredId');
var parameter = { id: getDoCredId };
$.ajax({
url: "/Doctor/ViewFile1",
type: "get",
dataType: "html",
data: parameter,
success: function (data) {
debugger;
if (data = true) {
debugger;
var getdoctorId = $(thisEvent).attr('docCredId');
var url = "/Doctor/ViewFile/" + getdoctorId;
window.open(url, "_blank");
}
else {
debugger;
showNotification("Error", "warning");
}
}
});
}
Below is my anchor tag HTML
<a title="View Attachment" docCredId = "' + getDocCredId + '" onclick="abc(this)"><i class="btn btn-web-tbl btn-warning fa fa-eye "></i></a>
Below is code behind
public bool ViewFile1(int id)
{
var document = _doctorService.GetDoctorCredentialDetails(id);
string AttachPath = ConfigPath.DoctorCredentialsAttachmentPath;
string strFileFullPath = Path.Combine(AttachPath, document.AttachedFile);
string contentType = MimeTypes.GetMimeType(strFileFullPath);
bool checkFileInFolder = System.IO.File.Exists(strFileFullPath);
if (checkFileInFolder == true)
{
return true;
}
else
{
return false;
}
}
public ActionResult ViewFile(int id)
{
var document = _doctorService.GetDoctorCredentialDetails(id);
string AttachPath = ConfigPath.DoctorCredentialsAttachmentPath;
string strFileFullPath = Path.Combine(AttachPath, document.AttachedFile);
string contentType = MimeTypes.GetMimeType(strFileFullPath);
bool checkFileInFolder = System.IO.File.Exists(strFileFullPath);
bool filedata = System.IO.File.ReadAllBytes(strFileFullPath).Any();
byte[] filedata1 = System.IO.File.ReadAllBytes(strFileFullPath);
var cd = new System.Net.Mime.ContentDisposition
{
FileName = document.FileName,
Inline = true
};
Request.HttpContext.Response.Headers.Add("Content-Disposition", cd.ToString());
return File(filedata1, contentType);
}
Since this is too long for a regular comment, I am posting this as an answer, although it isn't directly going solve the problem because I am not able to reproduce it, but might give some insights and let you check the differences with what happens in your code as compared with this simplified example.
Calling window.open() from jQuery ajax success callback works just fine: https://codepen.io/nomaed/pen/dgezRa
I used the same pattern as you did, without your server code but using jsonplaceholder.typicode.com sample API instead.
There are some issues with the code sample that you might want to consider, even though you didn't ask for comments about it and it's not directly related to your issue (probably):
if (data = true) means data will always be true. You probably mean to do a if (data === true) if you know it's a boolean value, or if (data) if you want to accept any truthy value (true, {}, "something", 42, etc). Judging by the Java code and how you define the response format in the jQuery ajax call, it looks like you're expecting the "data" variable result be an HTML and not a boolean. You might want to try and remove the dataType: "html" row and let jQuery set the data format according to what is coming back from the server, and/or send a JSON formatted response, as in a POJO of { result: true } for a successful response. Then make sure that data.result === true to be sure that you got what you expect.
You should probably add arbitrary data to tags DOM elements the data-* attributes and if you're using jQuery, access them using the .data() selector. White adding just random attributs with string values may work, it's considered an abuse of the HTML and DOM, and the data-* attributes are there specifically for adding any data.
In the abc() function you grab the value of the attribute in the beginning (var getDoCredId = $(thisEvent).attr('docCredId');) but in the callback you're trying to get the value once more. You really don't need it since the success() callback is a closure in the scope of the abc() function and it has access to the value already, so doing var getdoctorId = $(thisEvent).attr('docCredId'); in the callback is really not needed.
I'd also suggest naming getDoCredId variable just as docCredId. Having a "get" prefix usually means that it's a getter function or a reference to some getter. Likewise, the "thisEvent" argument of the main function should probably be called "callerElement" or something like that since it's not an event, it's an actual element that you're passing directly from the DOM when calling abc(this) in the onClick event handler of the <a> anchor. This is just to make the code clearer to understand for anyone who's reading it, and for yourself when you're coming back to it several months in the future and trying to figure out what's going on :)
Try adding async: false to your Ajax request
function abc(thisEvent) {
debugger;
var getDoCredId = $(thisEvent).attr('docCredId');
var parameter = { id: getDoCredId };
$.ajax({
async: false, // <<<----------- add this
url: "/Doctor/ViewFile1",
type: "get",
dataType: "html",
data: parameter,
success: function (data) {
debugger;
if (data = true) {
debugger;
var getdoctorId = $(thisEvent).attr('docCredId');
var url = "/Doctor/ViewFile/" + getdoctorId;
window.open(url, "_blank");
}
else {
debugger;
showNotification("Error", "warning");
}
}
});
}

Reading claims from another application using jquery

I have a static method in static class in MVC application that returns User Claims, when I access directly the url of this application,I am getting those values but when I access application url from another application using Javascript,it is not returning anything.I am not getting any error.It is returning empty result.I am also not getting CORS issue.i suspect it is something related to authentication & passing user credentials,both site is under same ADFS configuration
public static UserDetails GetUserDetails()
{
var userdetails = new UserDetails();
var objClaims = ((ClaimsIdentity)Thread.CurrentPrincipal.Identity).Claims;
foreach(var c in objClaims)
{
else if (c.Type == ConstantsHelper.emailAddress)
{
userdetails.Email = c.Value;
}
else if (c.Type == ConstantsHelper.userName)
{
userdetails.UserName = c.Value;
}
else if (c.Type == ConstantsHelper.shortName)
{
userdetails.ShortName = c.Value;
}
}
return userdetails;
}
Code to access it from another application.
function GetLoggedInUsermethod() {
var url = GetLoggedInUser;
$.ajax({
type: "GET",
url: url,
crossDomain: true,
success: function (json) {
},
error: function (e) {
}
});
}
If the calling application is hosted in different domain (different ports will qualify for different domains), then you may need to add the Access-Control-Allow-Origin header to the response with the value set to the calling application's domain for the call to succeed.
More details here.

UIWebView write to disk method

I am working on a UIWebView application and obtain some information from a server in the javascript code. I wish to write the JSON text to a file in the documents directory. The beginning part of my javascript file is:
WW.FS = {
init: function(animation, back, fn) {
var me = window.ww ? ww.fs : null;
if (me != null) {
PL.tellNative('pl:closeMore');
}
if (!me || !back) {
Ext.Ajax.request({
url: WW.getBS(),
method: 'POST',
params: {ajax: true, source: 'Touch', ID: 'INT'},
success: function(response) {
try {
data = JSON.parse(response.responseText); <--- want to write this to the documents directory!!
} catch(e) {
PL.indicatorOff();
return false;
}
I need to somehow get the variable "data" back to either the .m file from which I called the javascript file or write it to the documents directory so I can read it later. Would anyone know how to write the variable to the disk? I have been looking for a method to the data to the documents directory with no avail. Any help would be greatly appreciated.
The only way I know to get data from javascript in a UIWebView back to your native code is through the UIWebViewDelegate method webView:shouldStartLoadWithRequest:navigationType. Basically this call lets you filter URL load calls made within your UIWebView. You override this method and return YES if the load should proceed. The trick is to embed some string in the URL that would make the URL invalid and that you know means you are trying to pass data. Here's an example:
- (BOOL)webView:(UIWebView*)webView shouldStartLoadWithRequest:(NSURLRequest*)request navigationType:(UIWebViewNavigationType)navigationType
{
NSString *requestString = [[[request URL] absoluteString] stringByReplacingPercentEscapesUsingEncoding: NSUTF8StringEncoding];
NSArray *requestArray = [requestString componentsSeparatedByString:#":##key_val##"];
if ([requestArray count] > 1)
{
//...do your custom stuff here, all the values sent from javascript are in 'requestArray'
return NO;//abort loading since this is an invalid URL anyway
}
else
{
return YES;
}
}
Within your javascript add something like this:
function sendToApp(_key, _val)
{
var iframe = document.createElement("IFRAME");
iframe.setAttribute("src", _key + ":##key_val##" + _val);
document.documentElement.appendChild(iframe);
iframe.parentNode.removeChild(iframe);
iframe = null;
}
And so to send data from javascript to the native code you do something like this:
sendToApp('state', event.data);

Categories