Sub Resource Integrity for images using javascript - javascript

I recently learned about Sub Resource Integrity which prevents the execution of altered JS and CSS. Since the current implementation lacks the support for images I tried to experiment with my own implementation.
<img data-src="http://localhost:8888/4.jpg" alt="" data-hash="" class="image">
<img data-src="http://localhost:8888/2.jpg" alt="" data-hash="" class="image">
<img data-src="http://localhost:8888/3.jpg" alt="" data-hash="" class="image">
<script src="qwest.js"></script>
<script src="md5.min.js"></script>
<script>
var images = document.getElementsByClassName("image");
for( var i = 0, len = images.length; i < len; i++){
popHash(images[i]);
}
function popHash(image) {
qwest.get(image.dataset.src, {}, {responseType:"blob"})
.then(function (xhr, response) {
var src = window.URL.createObjectURL(response);
image.src = src;
image.dataset.hash = md5(src);
console.log(image.dataset.hash);
/* code to check the equality of hashes here */
})
}
</script>
The problem is each time I am getting a different MD5 hash. Please help me to find what I am doing wrong.
I am using JavaScript-MD5 (https://github.com/blueimp/JavaScript-MD5) for getting MD5 hash and Qwest.js (https://github.com/pyrsmk/qwest) for fetching the Image

With Slight Changes I was able to get the correct result. I used arrayBuffer instead of blob and a sha-256 hashing. I made a tiny library for the same.
https://github.com/ShopupStore/IntegrityChecker

Related

can I use JS to add a unix timestamp to <img> end of the src?

I need add the random int or unix timestamp to all img src="" whit class='avatar'
<img src="a.png" alt="" class="avatar">
<img src="b.png" alt="" class="avatar">
<img src="c.png" alt="" class="avatar">
I know I can use php to set it
<img src="a.png?<?php echo time();?>" alt="" class="avatar">
But I want to try Js to do that.
my code for try, but not work
<script>
var now = Date.now()
var img_src = document.querySelector(".avatar").src;
document.querySelector(".avatar").src = img_src+"?"+now;).
</script>
why add a random int or unix timestamp to the end of img src?
Because I using a CDN
when the user update some photos can't see the new photo on real time.
I prefer use JS don use server side.
the file name is fixed forever, can't change.
any other suggest?
You can get all the images with the querySelectorAll method on the document object.
const images = document.querySelectorAll(".avatar");
After that you can change the src attribute for each of them.
images.forEach((image) => {
image.src = image.src + "?random=" + Date.now();
});

retrieving gifs from tenor API json

i'm implementing this tenor API into my Site....the thing is that with this function I retrieve a single value single gif...How do I foreach() all of them?
How would need to be the html structure and the javascript loop
JAVASCRIPT/ JSON
function grab_data(anon_id)
{
// set the apikey and limit
var apikey = "*************";
var lmt = 8;
.....
// callback for trending top 10 GIFs
function tenorCallback_trending(responsetext)
{
// parse the json response
var response_objects = JSON.parse(responsetext);
top_10_gifs = response_objects["results"];
// load the GIFs -- for our example we will load the first GIFs preview size (nanogif) and share size (tinygif)
document.getElementById("preview_gif").src = top_10_gifs[1]["media"][0]["nanogif"]["url"];
document.getElementById("share_gif").src = top_10_gifs[6]["media"][0]["tinygif"]["url"];
return;
}
I would have this top_10_gifs variable loaded of content...how do I foreach it?
HTML
<h2 class="title">GIF loaded - preview image</h2>
<div class="container">
<img id="preview_gif" src="" alt="" style="">
</div>
<h2 class="title">GIF loaded - share image</h2>
<div class="container">
<img id="share_gif" src="" alt="" style="">
</div>
Depends on what exactly you're trying to do (which you haven't explained), but something like
response_objects.results.forEach((gifObj, i) => {
if (i >= 8) return;
// do something with each gifObj
document.querySelector('.container')
.appendChild(document.createElement('img'))
.src = gifObj.media[0].tinygif.url;
});
to iterate over all of them.

CDATA Issue Within Magento Rotator

So I'm currently developing a Magento Website. I set up a rotator using the code found here:
http://www.magentocommerce.com/wiki/4_-_themes_and_template_customization/cms_and_home_page/javascript_banner_rotator_for_home_page
If I put the code into the homepage it works as it's supposed to. However if I put the code within a static block CDATA forces itself into the code, breaking it. I'm unable to remove the CDATA as it keeps replacing itself. Code Below:
<script type="text/javascript">// <![CDATA[
var imgs1 = new Array("{{media url="wysiwyg/rotator-1-1.jpg"}}","{{media url="wysiwyg/rotator-1-2.jpg"}}","{{media url="wysiwyg/rotator-1-3.jpg"}}");
var lnks1 = new Array("http://www.example.com/","http://www.example.com/","http://www.example.com/");
var alt1 = new Array("That Looks Nice","That Looks Nice","That Looks Nice");
var currentAd1 = 0;
var imgCt1 = 3;
function cycle1() {
if (currentAd1 == imgCt1) {
currentAd1 = 0;
}
var banner1 = document.getElementById('adBanner1');
var link1 = document.getElementById('adLink1');
banner1.src=imgs1[currentAd1]
banner1.alt=alt1[currentAd1]
document.getElementById('adLink1').href=lnks1[currentAd1]
currentAd1++;
}
window.setInterval("cycle1()",4000);
// ]]></script>
<p><a id="adLink1" target="_top"> <img id="adBanner1" src="{{media url="wysiwyg/rotator-1-1.jpg"}}" alt="" width="235" height="250" border="0" /></a></p>
Any help would be appreciated.
You are commenting the javascript ending </script> tag, try putting </script> after the line CDATA ends.
Not sure about this, but worth a try.

Replace SRCs of Two Images with One Click

I am trying to do something that is slightly more complicated than I am used to, and I was hoping you guys could help me with this one... The website I am developing requires this type of Psudo
<script>
function FirstPic(){
document.titlepic.src = document.rep1.src
return
}
function SecPic(){
document.submitpic.src = document.rep2.src
return
}
</script>
// Calling Image Replacements
<img style="visibility:hidden;width:0px;height:0px;" name="rep1" src="title2.gif>
<img style="visibility:hidden;width:0px;height:0px;" name="rep2" src="submit2.gif>
// End of Calling Image Replacements
// Output Area
<img src="title.gif" name="titlepic">
<input type="radio" onclick="FirstPic();SecPic();updateProductPrice(this);parent.specs.location='<?php echo $options_item['base_var'] ?>.htm';">
<img src="submit.gif" name="submitpic">
// End of Output Area
You can replace the sources of as many images as you would like with a single click. And a single function, you don't need a function per each image.
demo
HTML:
<img src='source-img-1.jpg' class='s'>
<!-- as many source images as you would like -->
<button id='replace'>Replace</button>
<img src='destination-img-1.jpg' class='d'>
<!-- as many destination images as you have source images -->
JavaScript:
var r = document.getElementById('replace');
r.addEventListener('click', function(){
var s = document.querySelectorAll('.s'),
d = document.querySelectorAll('.d'),
l = s.length;
if(d.length != l) return;
for(var i = 0; i < l; i++) d[i].src = s[i].src;
}, false);
Also, use a CSS stylesheet, don't use inline styles.

Automatically loading a series of images sequentially in html

I have a html page that gets automatically refreshed every 1 ms. I did it using mata tag:
<html>
<head>
<title>My Page</title>
<meta http-equiv="refresh" content="0.001">
</head>
<body>
<img src=" 0.bmp" alt="Smiley face" height="100" width="200" />
</body>
</html>
Now my requirement is such that after every refresh I must load a new file. So in my folder I have files named: 0.bmp, 1.bmp, 2.bmp,... 1000.bmp, which will be loaded on the html file. i.e after every refresh a new file from the folder will be loaded. Basically the file name in
<img src=" 0.bmp" alt="Smiley face" height="100" width="200" />
will change from 0.bmp to 1...1000.bmp and so on.
How can we do this in html i.e change the file name dynamically?
Edited #1:
I have just realized that my problem is basically of animation. So given 1000 images stored in hard disk, I have to play them one by one on an HTML page. This should be as fast as possible. The only requirement is it must be on html pages, this is because these HTML pages will be accessed from a client in a network. the problem that I am thinking is slow playback because read/write to the disk may not be fast.
Edited # 2
After getting inputs from following answers, I was able to animate the images. The issue right now I am facing is the display rate is too small, and so fluctuations are coming up. I understand this is a problem of slow read/write from hard disk. So I guess if I can put these images in buffer i.e: System RAM, and write a html/js code to access the images from the RAM instead of the disk, the play back will be much faster. Can someone send me a sample code to, write images in RAM and use html/js code to access these images from RAM?
Note: as per the policy of stackoverflow, I am updating my question as and when I am solving various steps of the original problem.
What you are trying to do should not be done by refreshing continuously the web page, but by the use of Javascript.
Consider this method using JQUERY and setInterval():
See a working Fiddle Example!
HTML
<html>
<head>
<title>My Page</title>
</head>
<body>
<img src="path_to_image_01.jpg" alt="Smiley face" height="128" width="128" />
<img src="path_to_image_02.jpg" alt="Smiley face" height="128" width="128" />
<img src="path_to_image_03.jpg" alt="Smiley face" height="128" width="128" />
<img src="path_to_image_04.jpg" alt="Smiley face" height="128" width="128" />
</body>
</html>
JQUERY
$(document).ready(function() {
$('img:not(:first)').hide();
var refreshId = setInterval( function()
{
var $target = $('body img:first');
$target.hide().next().show();
$target.appendTo('body');
}, 1000);
});
What's being done
Hide all images
`$('img:not(:first)').hide();`
Initialize an interval of 1 sec that will collect the first image,
hide it, jump to the next image, show it, lastly move the previous
image to the end.
var refreshId = setInterval( function()
{
var $target = $('body img:first');
$target.hide().next().show();
$target.appendTo('body');
}, 1000);
This keeps on going animating the images every second that passes.
I am updating my answer based on a now different question.
You can use this plugin: https://code.google.com/p/jsmovie/ It does exactly what you want by animating a set of images.
Original Answer Below:
Although I'd agree with many of the other answers, it seems the OP needs to refresh the entire window instead of doing this via ajax without a page reload.
<img src="" alt="Smiley face" height="100" width="200" style="display:none" />
function getParameterByName(name)
{
name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
var regexS = "[\\?&]" + name + "=([^&#]*)";
var regex = new RegExp(regexS);
var results = regex.exec(window.location.search);
if(results == null)
return "";
else
return decodeURIComponent(results[1].replace(/\+/g, " "));
}
var imgIndex = 0;
$(document).ready(function() {
if (getParameterByName("index")!='') {
imgIndex = parseInt(getParameterByName("index"));
}
$('img').attr('src', imgIndex + '.bmp').show();
var refreshId = setInterval( function()
{
imgIndex++;
location.href = location.pathname + "?index=" + encodeURIComponent(imgIndex);
}, 1000); // 1 second update as needed
});
The following fiddle demonstrates this though I dont' have a serial set of images so the jsfiddle is a little different in that it updates an index of already set images forked from a previous answer but it does demonstrate the page reload.
http://jsfiddle.net/smf9w/1/
​
DON'T, really DON'T do this!!
Use JS instead. Use setInterval() and use a time span greater than 1m...
As others say, this is not the way to do it. But you can use cookie or localstorage on modern browsers.
function getData() {
var c = 0;
if ("localStorage" in window && null !== window.localStorage)
c = localStorage.count;
else {
count = document.cookie.split("count=");
c = c[1].split(";");
c = c[0];
}
return c;
}
function updateData(count){
if ("localStorage" in window && null !== window.localStorage)
localStorage.count = count;
else {
var e = new Date;
e.setTime(e.getTime() + 31536E6);
e = e.toGMTString();
document.cookie = "count=" + count + "; expires=" + e + "; path=/"
}
}
var count = getData();
document.write('<img src="'+ count +'".bmp" alt="Smiley face" height="100" width="200" />');
updateData(++count);
Code above is just a sample.

Categories

Resources