Changing images src by javascript - cache issue - javascript

I am building a web site, using jQuery.
Two major things:
I want to change picture (image src) manually, but sometimes the picture isn't changed (I am using right now chrome, but I want a general solution).
Also, I want to get the image width + height, after I load the picture.
(The picture is a file from the server - I just use different file name).
When changing the image by JavaScript/jQuery - I realized that when I change the image once, it is kept in memory, so I run into some problems.
I have found that the image is not uploaded the second time due to cache problem, so as I did some workaround, I realized that I need to do JavaScript command such as:
$("#id_image").attr("src", "pictures\\mypicture.jpg" + "?" + Math.random());
That's how I am changing manually the image.
By using the Math.random() I got a second problem:
If I wrote before Math.random() the line:
$("#id_image").width("auto");
$("#id_image").height("auto");
I don't get the height + width after using the Math.random(), so I put another line, and finally my code is:
$("#id_image").width("auto");
$("#id_image").height("auto");
$("#id_image").attr("src", "pictures\\mypicture.jpg");
$("#id_image").attr("src", "pictures\\mypicture.jpg" + "?" + Math.random());
alert("#id_image").width()); // **** returns 0 sometimes due cache
alert("#id_image").height()); // **** returns 0 sometimes due cache
Still, I have some problem (see remarks on asterisk), and I don't know how to always get the width + height of loaded image.

You could try setting onload handler before setting image src, this way, even your image is cached, this should give you correct image size:
$("#id_image").on('load',function(){
alert($(this).width());
alert($(this).height());
});
$("#id_image").attr("src", "pictures\mypicture.jpg");

VersionNumber = System.Configuration.ConfigurationManager.AppSettings["Version"];
//Caching Issues For JS
public static string JSVersionUpdate(string JsFile)
{
StringBuilder str = new StringBuilder();
str.Append(GetQualifiedPath(JsFile));
str.Append("?Version=");
str.Append(VersionNumber);
return str.ToString();
}
public static void DiscardVersion()
{
VersionNumber = null;
}
//get Full Path for JS File
private static string GetQualifiedPath(string path)
{
var httpRequestBase = new System.Web.HttpContextWrapper(System.Web.HttpContext.Current);
path = path.Replace("~", string.Empty);
string appPath = string.Empty;
if (httpRequestBase != null)
{
//Formatting the fully qualified website url/name
appPath = string.Format("{0}://{1}{2}{3}{4}",
httpRequestBase.Request.Url.Scheme,
httpRequestBase.Request.Url.Host,
httpRequestBase.Request.Url.Port == 80 ? string.Empty : ":" + httpRequestBase.Request.Url.Port,
httpRequestBase.Request.ApplicationPath,
path);
}
appPath = appPath.TrimEnd('/');
return appPath;
}
}
In UI Page : script src="JSVersionUpdate("~/Scripts/Application/Abc.js")"
O/p : ~/Scripts/Application/Abc.js/version=1.0
Browser request for JS Files from server only if Version is Different else it will cached out.Now i don't need to tell someone to clear the cache again and again after deployment.Only thing i do is i change Version Number in Web COnfig.
Same can be applied to Image As well !! Hope it Helps

Related

Update CSS background-image Only When Source Image Changes Using Javascript

Is it possible to update the CSS image pointed by the passed-in url in "backgound-image: \"<some-url>\" in Javascript only when the source image is changed in the server. I.e. cache the image, and then retrieve the image from the server when it's needed to be reload and compare it with the cached image. Then, reload it when it's updated only. I know that in order to refresh an image in CSS through Javascript, the image must have a different string after the "?" in the image source, and one way to do so is by using the current time returned by Date.getTime method after "?". E.g. (I got this method from here https://stackoverflow.com/a/1077051/7000599):
$(".some-css-class").css("backgound-image", "url(" + "\"" + some_source + "?" + new Date().getTime() + "\"" + ")");
However, I would like to call the above logic when I need to update the background-image only when it detect the image has been changed. So is there a way to detect such changes?
Give each image a unique id and then poll the server every so often to see if there's a new id, and if so, change the underlying image.
You may add API to server side which returns some hash value for image content. So when you put the image for first time - add hash-value for specific image after '?'.
$(".come-css-class").css("backgound-image", "url(" + "\"" + some_source + "?" + imageHash + "\"" + ")");
Than from time to time call the hash API and replace background-image property. When image will be updated on server - it will return new hash-value - so css will reload the image.
To automatically update the image through JavaScript itself (without relying on any back-end script), you would need to poll the server periodically to check whether the modification date was greater than a cached copy of the image. You would then need to refresh the page if this was the case.
This would be done similar to the following:
var previous = null;
var current = null;
var image_url = 'IMAGE URL';
setInterval(function() {
var req = new XMLHttpRequest(); // Poll the server
req.open("HEAD", image_url, false);
req.send(null);
if (req.status == 200) {
current = req.getResponseHeader('Last-Modified'); // Get modification time
}
if (previous && current && previous !== current) { // If it's been modified
location.reload(); // Refresh
}
previous = current; // Store the 'new' image information
$(".come-css-class").css("background-image", "url(" + "\"" + image_url + "\""); // Update the image
}, 2000); // Repeat every two seconds
Also note that you called it backgound-image in your question. You need to ensure that you call it background-image in order to function correctly.
Hope this helps! :)
Similar to a reply comment to #Nosyara, I think the better approach to this problem I have found so far is by using the HTTP header ETag to detect whether the source image (or file as well) is changed from the last cached file. I think #ObsidianAge's answer would also work (i.e. using the Last-Modified header), but for some reason it doesn't show any changes when the source image (or file) is changed. I did a simple local Apache server and simple webpage with a Javascript onInterval event to console.log whether the file has changed or not, but it doesn't seem the case. So apparently ETag is a way to do it. Here's the Wikipedia page explaining it's purposes (it has other purposes too): https://en.wikipedia.org/wiki/HTTP_ETag.

Adding a javascript file to an already-running Java FX webengine

I have a Java application that is running a Java FX webengine (the end goal of all of this is to dynamically draw a D3.js plot). I'd like to be able to add new javascript files to it while it's already running, and then ideally unload them again when the javascript tells it to.
This has the effect of making some functionality available to the user or not (drawing certain features) without having to load all of the code in at once. It also helps me avoid future headaches with a forest of brittle if/then statements inside my javascript.
Question 1: Is "unloading" files from a running webengine even possible? At least, possible without redrawing the whole thing. I'm pretty sure that calling loadContent() with my new filepaths will make them available the way that I want, but I haven't come across anything talking about how you can remove existing source code from your HTML block.
Question 2: Any recommendations on how to elegantly approach feeding the extra sources into the webView? My thought process right now is stuck on brute force, but I haven't been even been able to brute force my way to a solution that works, so maybe I'm barking up the wrong tree.
Question 3: Is this even a good idea? It's possible to do this solely in the Javascript, but I want the appearance and disappearance of options directly tied to a java-side feature that's later going to be executed from the class Bridge, the same place I'm trying to load new content from right now.
I asked a lot of questions, but any help is appreciated!
Right now I am setting up the webengine's content like so:
final ResourceExtractor RESOURCE_EXTRACTOR
= new ResourceExtractor(JavaScriptPlot.class);
// prepare the local URI for d3.js
final URI D3_JS_URI = RESOURCE_EXTRACTOR
.extractResourceAsPath("d3.min.js")
.toUri();
// prepare the local URI for numeric.js
final URI NUMERIC_JS_URI = RESOURCE_EXTRACTOR
.extractResourceAsPath("numeric.min.js")
.toUri();
// prepare the local URI for topsoil.js
final URI TOPSOIL_JS_URI = RESOURCE_EXTRACTOR
.extractResourceAsPath("topsoil.js")
.toUri();
// build the HTML template (comments show implicit elements/tags)
HTML_TEMPLATE = (""
+ "<!DOCTYPE html>\n"
// <html>
// <head>
+ "<style>\n"
+ "body {\n"
+ " margin: 0; padding: 0;\n"
+ "}\n"
+ "</style>\n"
// </head>
+ "<body>"
+ "<script src=\"" + D3_JS_URI + "\"></script>\n"
+ "<script src=\"" + NUMERIC_JS_URI + "\"></script>\n"
+ "<script src=\"" + TOPSOIL_JS_URI + "\"></script>\n"
+ "<script src=\"%s\"></script>\n" // JS file for plot
// </body>
// </html>
+ "").replaceAll("%20", "%%20");
The source path to replace %s is created here:
public class BasePlot extends JavaScriptPlot {
private static final ResourceExtractor RESOURCE_EXTRACTOR
= new ResourceExtractor(BasePlot.class);
private static final String RESOURCE_NAME = "BasePlot.js";
public BasePlot() {
super(
RESOURCE_EXTRACTOR.extractResourceAsPath(RESOURCE_NAME),
new BasePlotDefaultProperties());
}
}
And then later I take a file path already extracted as a resource, sourcePath, and insert it into the HTML block:
String buildContent() {
return String.format(HTML_TEMPLATE, sourcePath.toUri());
}
Then I build my web view using the return value of buildContent()
private void initializeWebView() {
runOnFxApplicationThread(() -> {
// initialize webView and associated variables
webView = new WebView();
webView.setContextMenuEnabled(false);
WebEngine webEngine = webView.getEngine();
webEngine.getLoadWorker().stateProperty().addListener(
(observable, oldValue, newValue) -> {
if (newValue == SUCCEEDED) {
if (new IsBlankImage().test(screenCapture())) {
webEngine.loadContent(buildContent());
}
topsoil = (JSObject) webEngine.executeScript("topsoil");
topsoil.setMember("bridge", new Bridge());
}
});
// asynchronous
webEngine.loadContent(buildContent());
});
}
And the Javascript can fire off the method in the class below to trigger the change. Right now it's manually creating a hardcoded resource, but once I work out once going wrong I'll make this part more elegant/logically organized.
//loads appropriate JS files into webview based on BasePlot's isotope type
public class Bridge {
final URI ISOTOPE_URI = ISOTOPE_RESOURCE_EXTRACTOR
.extractResourceAsPath("Concordia.js")
.toUri();
String finalHtml = buildContent().concat("<script src=\""+ISOTOPE_URI.toString()+"\"></script>\n");
webView.getEngine().loadContent(finalHtml);
}
}
The loadContent() above is giving me an application thread error: "ReferenceError: Can't find variable: topsoil"

Issues in developing web scraper

I want to develop a platform where users can enter a URL and then my website will open the webpage in an iframe. Now the user can modify his website by simply right clicking and I will provide him options like "remove this element", "copy this element". I am almost through. Many of the websites are opening perfectly in iframe but for a few websites some errors have shown up. I could not identify the reason so asking for your help.
I have solved other issues like XSS problem.
Here is the procedure I have followed :-
Used JavaScript and sent the request to my Java server which makes connection to the URL specified by the user and fetches the HTML and then use Jsoup HTML parser to convert relative URLs into absolute URLs and then save the HTML to my disk in Java. And then I render the saved HTML into my iframe.
Is somewhere wrong ?
A few websites are working perfectly but a few are not.
For example:-
When I tried to open http://www.snapdeal.com it gave me the
Uncaught TypeError: Cannot read property 'paddingTop' of undefined
error. I don't understand why this is happening..
Update
I really wonder how this is implemented? # http://www.proxywebsites.in/browse.php?u=Oi8vd3d3LnNuYXBkZWFsLmNvbQ%3D%3D&b=13&f=norefer
2 issues, pick any you like:
your server side proxy code contains bugs
plenty of sites have either explicit frame-break code or at least expect to be top level frame.
You can try one more thing. In your proxy script you are saving your webpage on your disk and then loading into iframe. I think instead of loading the page you saved on disk in iframe try to open that page in browser. All those sites that restirct their page to be loaded into iframe will now get opened without any error.
Try this I think it an work
My Proxy Server side code :-
DateFormat df = new SimpleDateFormat("ddMMyyyyHHmmss");
String dirName = df.format(new Date());
String dirPath = "C:/apache-tomcat-7.0.23/webapps/offlineWeb/" + dirName;
String serverName = "http://localhost:8080/offlineWeb/" + dirName;
boolean directoryCreated = new File(dirPath).mkdir();
if (!directoryCreated)
log.error("Error in creating directory");
String html = Jsoup.connect(url.toString()).get().html();
doc = Jsoup.parse(html, url);
links = doc.select("link");
scripts = doc.select("script");
images = doc.select("img");
for (Element element : links) {
String linkHref = element.attr("abs:href");
if (linkHref != "") {
element.attr("href", linkHref);
}
}
for (Element element : scripts) {
String scriptSrc = element.attr("abs:src");
if (scriptSrc != "") {
element.attr("src", scriptSrc);
}
}
for (Element element : images) {
String imgSrc = element.attr("abs:src");
if (imgSrc != "") {
element.attr("src", imgSrc);
log.info(imgSrc);
}
}
And Now i am just returning the path where i saved my html file
That's it about my server code

Expand partial URL into full (like in image.src)

I'm trying to write an onerror handler for images that replaces them with a loading image and then periodically tries to reload them. The problem I'm having is that if the loading image fails to load, it goes into an infinite loop of failure. I'm trying to deal with this by checking if the URL is the loading image:
if(photo.src != loadingImage) {
// Try to reload the image
}
Unfortunately, loadingImage can be a relative URL (/images/loadingImage.jpg), but photo.src is always a full URL (http://example.com/images/loadingImage.jpg). Is there any way to generate this full URL without passing the function any more information? Obviously I could pass it the host name, or require full URLs, but I'd like to keep this function's interface as simple as possible.
EDIT:
Basically what I want is to guarantee that if I do photo.src = loadingImage, that this will be true: photo.src === loadingImage. The constraint is that I know nothing about loadingImage except that it's a valid URL (it could be absolute, relative to the server, or relative to the current page). photo.src can be any (absolute) URL, so not necessarily on the same domain as loadingImage.
Here's a couple methods people have used to convert relative URLs to absolute ones in javascript:
StackOverflow - Getting an absolute URL from a relative one
Debuggable.com - Relative URLs in Javascript
Alternatively, have you considered doing the opposite - converting the absolute URL to a relative one? If loadingimage always contains the entire path section of the URL, then something like this would probably work:
var relativePhotoSrc = photo.src;
if (relativePhotoSrc.indexOf("/") > 0 && relativePhotoSrc.indexOf("http://") == 0) {
relativePhotoSrc = relativePhotoSrc.replace("http://", "");
relativePhotoSrc = relativePhotoSrc.substring(relativePhotoSrc.indexOf("/"), relativePhotoSrc.length);
}
alert(relativePhotoSrc);
if (relativePhotoSrc != loadingImage && photo.src != loadingImage) {
// Try to reload the image
}
There's probably a slightly more efficient/reliable way to do the string manipulation with a regular expression, but this seems to get the job done in my tests.
How about this? The photo should either be a full URL or relative to the current document.
var url;
// There probably other conditions to add here to make this bullet proof
if (photo.src.indexOf("http://") == 0 ||
photo.src.indexOf("https://") == 0 ||
photo.src.indexOf("//") == 0) {
url = photo.src;
} else {
url = location.href.substring(0, location.href.lastIndexOf('/')) + "/" + photo.src;
}
Just check if they end with the same string:
var u1 = '/images/loadingImage.jpg';
var u2 = 'http://example.com/images/loadingImage.jpg'
var len = Math.min(u1.length, u2.length);
var eq = u1.substring(u1.length - len) == u2.substring(u2.length - len);

How to resolve the C:\fakepath?

<input type="file" id="file-id" name="file_name" onchange="theimage();">
This is my upload button.
<input type="text" name="file_path" id="file-path">
This is the text field where I have to show the full path of the file.
function theimage(){
var filename = document.getElementById('file-id').value;
document.getElementById('file-path').value = filename;
alert(filename);
}
This is the JavaScript which solve my problem. But in the alert value gives me
C:\fakepath\test.csv
and Mozilla gives me:
test.csv
But I want the local fully qualified file path. How to resolve this issue?
If this is due to browser security issue then what should be the alternate way to do this?
Some browsers have a security feature that prevents JavaScript from knowing your file's local full path. It makes sense - as a client, you don't want the server to know your local machine's filesystem. It would be nice if all browsers did this.
Use
document.getElementById("file-id").files[0].name;
instead of
document.getElementById('file-id').value
I use the object FileReader on the input onchange event for your input file type! This example uses the readAsDataURL function and for that reason you should have an tag. The FileReader object also has readAsBinaryString to get the binary data, which can later be used to create the same file on your server
Example:
var input = document.getElementById("inputFile");
var fReader = new FileReader();
fReader.readAsDataURL(input.files[0]);
fReader.onloadend = function(event){
var img = document.getElementById("yourImgTag");
img.src = event.target.result;
}
If you go to Internet Explorer, Tools, Internet Option, Security, Custom, find the "Include local directory path When uploading files to a server" (it is quite a ways down) and click on "Enable" . This will work
I am happy that browsers care to save us from intrusive scripts and the like. I am not happy with IE putting something into the browser that makes a simple style-fix look like a hack-attack!
I've used a < span > to represent the file-input so that I could apply appropriate styling to the < div > instead of the < input > (once again, because of IE). Now due to this IE want's to show the User a path with a value that's just guaranteed to put them on guard and in the very least apprehensive (if not totally scare them off?!)... MORE IE-CRAP!
Anyhow, thanks to to those who posted the explanation here: IE Browser Security: Appending "fakepath" to file path in input[type="file"], I've put together a minor fixer-upper...
The code below does two things - it fixes a lte IE8 bug where the onChange event doesn't fire until the upload field's onBlur and it updates an element with a cleaned filepath that won't scare the User.
// self-calling lambda to for jQuery shorthand "$" namespace
(function($){
// document onReady wrapper
$().ready(function(){
// check for the nefarious IE
if($.browser.msie) {
// capture the file input fields
var fileInput = $('input[type="file"]');
// add presentational <span> tags "underneath" all file input fields for styling
fileInput.after(
$(document.createElement('span')).addClass('file-underlay')
);
// bind onClick to get the file-path and update the style <div>
fileInput.click(function(){
// need to capture $(this) because setTimeout() is on the
// Window keyword 'this' changes context in it
var fileContext = $(this);
// capture the timer as well as set setTimeout()
// we use setTimeout() because IE pauses timers when a file dialog opens
// in this manner we give ourselves a "pseudo-onChange" handler
var ieBugTimeout = setTimeout(function(){
// set vars
var filePath = fileContext.val(),
fileUnderlay = fileContext.siblings('.file-underlay');
// check for IE's lovely security speil
if(filePath.match(/fakepath/)) {
// update the file-path text using case-insensitive regex
filePath = filePath.replace(/C:\\fakepath\\/i, '');
}
// update the text in the file-underlay <span>
fileUnderlay.text(filePath);
// clear the timer var
clearTimeout(ieBugTimeout);
}, 10);
});
}
});
})(jQuery);
On Chrome/Chromium based apps like electron you can just use the target.files:
(I'm using React JS on this example)
const onChange = (event) => {
const value = event.target.value;
// this will return C:\fakepath\somefile.ext
console.log(value);
const files = event.target.files;
//this will return an ARRAY of File object
console.log(files);
}
return (
<input type="file" onChange={onChange} />
)
The File object I'm talking above looks like this:
{
fullName: "C:\Users\myname\Downloads\somefile.ext"
lastModified: 1593086858659
lastModifiedDate: (the date)
name: "somefile.ext"
size: 10235546
type: ""
webkitRelativePath: ""
}
So then you can just get the fullName if you wanna get the path.
Note that this would only work on chrome/chromium browsers, so if you don't have to support other browsers (like if you're building an electron project) you can use this.
I came accross the same problem. In IE8 it could be worked-around by creating a hidden input after the file input control. The fill this with the value of it's previous sibling. In IE9 this has been fixed aswell.
My reason in wanting to get to know the full path was to create an javascript image preview before uploading. Now I have to upload the file to create a preview of the selected image.
If you really need to send the full path of the uploded file, then you'd probably have to use something like a signed java applet as there isn't any way to get this information if the browser doesn't send it.
Use file readers:
$(document).ready(function() {
$("#input-file").change(function() {
var length = this.files.length;
if (!length) {
return false;
}
useImage(this);
});
});
// Creating the function
function useImage(img) {
var file = img.files[0];
var imagefile = file.type;
var match = ["image/jpeg", "image/png", "image/jpg"];
if (!((imagefile == match[0]) || (imagefile == match[1]) || (imagefile == match[2]))) {
alert("Invalid File Extension");
} else {
var reader = new FileReader();
reader.onload = imageIsLoaded;
reader.readAsDataURL(img.files[0]);
}
function imageIsLoaded(e) {
$('div.withBckImage').css({ 'background-image': "url(" + e.target.result + ")" });
}
}
seems you can't find the full path in you localhost by js, but you can hide the fakepath to just show the file name. Use jQuery to get the file input's selected filename without the path
The best solution for this, I've found, is to use a middleware like Multer. Here's a quick rundown:
npm i multer
Add enctype="multipart/form-data" to your html form.
In your backend dock where you're making your post request, require multer (const multer = require('multer'))
In the same dock, set your upload destination: const upload = multer({dest:'uploas/'}). This will automatically create a local folder called 'uploads' where your files will be added. The code I've included shows you how to upload to your local disk storage. If you're using cloud storage (e.g. AWS, Azure, Cloudinary etc.) you can check out the Multer docs to see how to manage that. There aren't too many extra steps though.
in your post request, add 'upload.single' (for one file) or 'upload.array' (for multiple files), like this:
router.post('/new', upload.single('image'), async function(req, res) { //'image' should be the name of the input you're sending in the req.body
console.log(req.file) //note, if you're using 'upload.array', this should be 'req.files'
});
the req.file will have a full path name that you can use in your post request. For more information, check out the Multer docs:
https://www.npmjs.com/package/multer
I hope this helps!
You would be able to get at least temporary created copy of the file path on your machine. The only condition here is your input element should be within a form
What you have to do else is putting in the form an attribute enctype, e.g.:
<form id="formid" enctype="multipart/form-data" method="post" action="{{url('/add_a_note' )}}">...</form>
you can find the path string at the bottom.
It opens stream to file and then deletes it.
Hy there , in my case i am using asp.net development environment, so i was want to upload those data in asynchronus ajax request , in [webMethod] you can not catch the file uploader since it is not static element ,
so i had to make a turnover for such solution by fixing the path , than convert the wanted image into bytes to save it in DB .
Here is my javascript function ,
hope it helps you:
function FixPath(Path)
{
var HiddenPath = Path.toString();
alert(HiddenPath.indexOf("FakePath"));
if (HiddenPath.indexOf("FakePath") > 1)
{
var UnwantedLength = HiddenPath.indexOf("FakePath") + 7;
MainStringLength = HiddenPath.length - UnwantedLength;
var thisArray =[];
var i = 0;
var FinalString= "";
while (i < MainStringLength)
{
thisArray[i] = HiddenPath[UnwantedLength + i + 1];
i++;
}
var j = 0;
while (j < MainStringLength-1)
{
if (thisArray[j] != ",")
{
FinalString += thisArray[j];
}
j++;
}
FinalString = "~" + FinalString;
alert(FinalString);
return FinalString;
}
else
{
return HiddenPath;
}
}
here only for testing :
$(document).ready(function () {
FixPath("hakounaMatata:/7ekmaTa3mahaLaziz/FakePath/EnsaLmadiLiYghiz");
});
// this will give you : ~/EnsaLmadiLiYghiz

Categories

Resources