Programm that tracks changes on web page - javascript

I have a web page that has several images on it and a script in it which changes picture of one random image once in some time interval. Script changes the image by rewtiting its file in the cash an updating it on the page. So url of the image picture doesnt chage in html code:
socket.on("banner", function(info) {
banName = "banner" + info.bid;
ban = document.getElementById(banName).getContext('2d');
var img = new Image();
img.src = 'data:image/jpg;base64,' + info.image;
img.onload = function(){ban.drawImage(img, 0, 0);};
});
How can I track image change using for example C#, when the page is in the browser?

As a last resort, retrieve the image periodically and load it into a byte array. Checking changes is just a matter of checking if the byte array has changed.
edit:
It seems the hard part is about how can one retrieve the image data. Without any javascript code in the browser, use C# to establish a websocket connection to mimic the behavior of javascript.
But I think it would be easier done by modifying the javascript code in the browser.

Related

Adding img.crossOrigin = "*" interferes with img.complete

I have a function that reads map tile images. I want to keep track of whether or not a certain image has already been cached. I'm using this function from this thread:
function is_cached(src) {
var image = new Image();
image.src = src;
return image.complete;
}
This was working great. But then I needed to do some image processing. In order to copy the image data to a canvas and process it pixel by pixel, I need to use CanvasRenderingContext2D.drawImage(image, 0, 0). But it bugs me with a cross-origin error. So I can add a image.crossOrigin = "*", which solves that problem, and I can write to a canvas and do the image processing I need. That bit looks like this:
imageOutput.crossOrigin = "*"
var demCtx;
imageOutput.onload = function(){
var c = document.createElement('canvas')
c.width = c.height = 256
demCtx = c.getContext('2d')
demCtx.drawImage(imageOutput, 0, 0)
var imageData = demCtx.getImageData(0, 0, 256, 256)
}
The issue that arises is that every time I run the larger function which contains these two bits of code, the is_cached function returns false every time, except the first time. But I know that even though is_cached is returning false, the images are indeed cached, as they are loading with 0 lag (as opposed to when a novel image is called and it takes a moment to grab it from the server).
Why might .crossOrigin = "*" be interfering with the .complete status of an image?
This is happening within an ObservableHQ notebook. Might that have something to do with it? ObservaleHQ gets weird sometimes.
ObservableHQ Notebook with the problem
You can find this code in the getTileUrl cell at the bottom. This notebook is not yet finished. You can see the cached status at the Tile Previously Cached line after you click around the map of submit changes to the inputs.
Thanks for reading.
Maybe fetch api can enforce cache using the param {cache:"force-cache"}, however images should be cached as expected. You can fetch the image and pass its blob as an image source.
replace your imageOutput.src with
imageOutput.src = URL.createObjectURL(await fetch(imageUrl, {cache:"force-cache"}).then(r => r.blob()));
make your getTileURL function async as we have to await fetch and blob to be ready to be passed as image source
async function getTileURL(latArg, lngArg, zoomArg) {
Use devtools to inspect network and see tile images coming from disk cache
edit:
just try your original code and inspect network via devtools. The tiles images are cache as expected. So no need to hack into fetch blob src.

How to take a snapshot of webpage from the url?

I want to take a snapshot of the webpage from the url. The url is an html web page which is dynamic. Basically we needed an img of that webpage.
I thought to convert the html page to image in c# but din't work.
I first read the html using streamreader and using NReco.ImageGenerator tried to convert into bytes and finally image. This isnt working.
Finally I am trying to convert html to canvas using javascript from inside the html web page.
function report() {
let region = document.querySelector("body");
html2canvas(
$('body'),
{allowTaint: true, logging: true,'onrendered': function (canvas)
{}}).then( //getting problem here at then
function (canvas) {
let jpgUrl = canvas.toDataURL();
console.log(jpgUrl);
var text = "bottom-right Brochure1";
var imageName = text + '.jpg';
download(jpgUrl,imageName, "image/png");
}
Code explained - It will take a snpashot of the body element in the html page using js. Take the url and create the canvas from the url. and automatically download. But i face a issue ------- " html2canvas(...),then is not a function" .. I dont know why its happening. Please help.
Because of Cross-Origin Resource Sharing (CORS) restrictions in all modern browsers, this can't be done purely on the clientside. You need something on the server-side to accomplish this. To do it in javascript on the server use NodeJS there are several npm packages that can help like: node-server-screenshot, PhantomJS etc

Javascript: How to check if image is already cached

I just started to learn a little bit of JavaScript and i wondered if there is a way to check if an image is already loaded to cache.
In my script im loading some random images from another webpage and display them.
When the same image will be displayed the second time, the script won't use the already loaded image, but instead load the same image again, so that there are two of them stored in my cache.
Now I want to check if the image is already stored in cache and if so, use the cached one instead of loading it again.
My code:
<script>
var img = document.createElement('img');
var index;
//On Click create random 3digit number between 1 and 100
document.getElementById('image').onclick = function(){
var index = '' + Math.floor(Math.random() * 100 +1);
while(index.length < 3) {
index = '0' + index;
}
loadImages(index);
};
//Load the image with the created number
function loadImages(id) {
var src = 'someWebPage/' + id +'.png';
img.onload = function () {
document.getElementById('image').getContext("2d").drawImage(img, 0, 0, 300, 300);
}
img.src = src;
}
</script>
Picture of my cache:
As you can see 030.png and 032.png are twice in cache.
Hope you can give me some advice.
EDIT:
Just for anyone else that faces this problem, it actually isnĀ“t one at all.
Chrome already did everything right, i only did not notice.
As you can see in the column Size the pictures were already loaded from my cache.
The way caching (in this context) is handled is by the browser negotiating with the server using a set of headers to basically tell the server "I already have this version of this resource", to which the server can then respond "OK, that is still valid, no need to download anything new". So you shouldn't be concerned about the caching in the JavaScript side, but instead make sure you are setting the correct Cache-Control headers on the server side. There are likely already questions/answers for your server/framework of choice on how to setup the caching there.

fetch image url at fixed intervals using javascript

I am a complete beginner in javascript so I don't even know where to begin. I have a URL that displays a .jpg snapshot. It is served from a video server. I would like to take the image and display it on a webpage with the image being refreshed every 2 seconds. The image will be displayed in a div container with id="snapshot"
Any help or guidance will be greatly appreciated.
For your html, you do the following:
<div id="snapshot"><img/></div>
Then in your JavaScript you do the following:
var url = "some url somewhere";
var snapshotImg = document.querySelector('#snapshot > img');
var updateInterval = setInterval(updateImage, 2000); //start the update every 2 seconds
updateImage(); //immediately update the image
function updateImage(){
snapshotImg.src = url + "?"+ new Date().getTime();
}
In the 'updateImage' function, I added a ? and a time hash to the url so that each time it sets the source, the srcurl is unique. If you don't make it unique each time, the browser will cache the image from the first request, and it won't ever update the image. So, you have to make the url unique, and you that by adding a hash, that is arbitrary, to the end of the url. I hope that makes sense.

Getting size of javascript preloaded image

I'm trying to preload a number of images generated on the server to a small website. The preloading is done using setWindowTimeout and uses an Image object, sets the onload callback and then applies the new request uri.
For some requests, the server may have to signal that the image is 'unchanged' and I'm doing it by sending done a small 1x1 pixel gif (seems like I need to send an actual image, returning empty content will cause the Image object to not fire onload). In my onload handler I would like to determine the size of the fetched image and then determine if I should update the visual image with the given image.
Below is a snippet of my current solution (the output is a div to help debug):
refresh: function() {
var newSrc = '/screenshot.ashx?tick=' + new Date().getTime();
var imgObj = new Image();
var self = this;
// this is called when load is done
imgObj.onload = function() {
//if (imgObj.complete)
// return;
if (imgObj.width > 1 && imgObj.height > 1) {
output.innerHTML += '<br/>Updating image:' + newSrc;
img.src = newSrc; //fiddler shows no reload here, read from cache
}
else {
output.innerHTML += '<br/>Empty image:' + newSrc;
}
self.setupNewRefresh();
};
output.innerHTML += '<br/>Loading image:' + newSrc;
imgObj.src = newSrc;
},
I seem to have two problems:
a) the imgObj.complete is false when the function is first called but it is only called once (hence my commenting it out) and
b) I can't seem to rely on the width or height property of the image when loaded. From my tests of fetch the 1x1 pixel, it sometimes reads out 50 which seems to be default when creating a new Image() and it sometimes reads out the correct size of 1.
My ultimate goal is to have a small chunk of javascript logic that queries the server for a new image periodically, does nothing if nothing new has happened (1 pixel image) or loads the new image. I might be going about it the wrong way here or have overlooked important properties or calls, so I'm happy to receive feedbacks.
EDIT: upon suggestion from mplungjan, I preloaded into a hidden div instead, which helped me with problem b). Still no solution to problem a) though; reports complete = false once and is not called again
I'll go ahead and answer my own question.
Preloading the image into a hidden element in the DOM instead of a code-level element was the trick for actually getting correct sizes (thanks mplungjan). The a) issue, namely the complete event, remains unsolved.
As a side note I ended up using the XMLHttpRequest instead as it allowed by to look at the size of the payload returned.

Categories

Resources