Show an alert when image changes on website - javascript

I have a GitHub pages site with an image on it. I am trying to have the webpage show an alert whenever I push a change to the website.
My approach so far has been to implement an auto-refresh function:
setTimeout(function(){ location.reload(); }, 60000);
This will auto-update every minute, catching all of the changes that I make. However, I need to show an alert whenever the content of the page changes. It is important to keep in mind that the content will not change upon every refresh -- maybe only every 10 minutes (when I push changes).
I think the way to do this would be to store the name of the image and then look to see if the image name changes at every refresh -- and if the name did change, then show the alert. I have been reading about something called LocalStorage, but I'm not sure how to approach storing the name of a file -- I'm sort of new to JS/HTML.
Is using LocalStorage the best approach to this problem? What are other alternatives/simple ways to implement this on a GitHub page?
Thanks in advance.

If I clearly understand what you need to implement, I'd suggest you to read about MutationObserver in JavaScript. This class tracks all the changes, that are made to binded element. Here's the code and working demo:
<html>
<body>
<p>
Some content
</p>
</body>
<script>
// select the target node
var element = document.getElementsByTagName('p')[0];
// create an observer instance
var observer = new MutationObserver(function(mutations) {
alert("Some changes were made");
});
// configuration of the observer:
var config = { childList: true}; // ,subtree: true, characterData: true
// pass in the target node, as well as the observer options
observer.observe(element, config);
setInterval(function () { // here you can make your changes programatically
element.innerHTML += "New content";
}, 2000)
</script>
</html>

You can also use cookies, i.e. store in a cookie the last "version" of whatever - where "version" can be a string, a number etc.
This has the advantage that it also gets sent to the server, so you may generate the alert layout/code directly on the server.
Check https://github.com/js-cookie/js-cookie for a script simplifying this.
Another alternative is to implement on the server a script that responds whether the content changed. Something like http://foo.bar/changed?lastVer=XXXX which can return a JSON like {changed:true,message:'We have changed the change'}. You would retrieve this via ie. jQuery.getJSON() or vanilla XMLHttpRequest, and if it's the case show the message to the user and then reload the page. But this would require making a runnable server script somewhere.
A third option would be to load the page into, say, a hidden IFRAME, check if the image or content changed and if so transplant only the image - or a certain piece of content - to the main page without refreshing it. Or maybe refresh it. The idea is to load the page in an IFRAME and detect there if something has changed.

Related

What to do if $(window).load(function(){}); is too early

I need to trigger a piece of code after every single bits are done downloading. The script works if injected after everything is loaded, but how do I trigger that automaticly?
My script is:
var divId = "jwplayer-0_wrapper";
if ($('#' + divId).length == 1) {
myReg = /https?:\/\/www\.youtube\.com\/watch\?v=[^"]+/;
var plainText = $('#' + divId).parent().children('script').text();
var url = plainText.match(myReg);
if (url !== null) {
window.location = url;
};
};
It is used to skip certain site that decide to use the JW player witch I find horribly buggy. So it looks for a div with the indication of the JW player and if there's one, it finds the link to the original youtube video and directly goes there.
Its triggered By Google Chrome Add-on named Javascript Injector and I apply the script on every page I visit. The plug in work perfectly well on sites like www.ayoye.co and www.veuxturire.com. But on other sites, that uses the same pathern, it seems that the script is triggerd too early. For example there www.mondedestars.com and www.lesautos.ca triggers it too early.
If I use the "inject now" fonction of the Add on after the page is really done loading, then it redirects me to the youtube page as expected. I am lost on the why it works some where and not were else.
I'm not trying to understand every single website here, I'd prefer make it dynamicly triggered after the page has done loading everything from its php, ajax, script, flash, html and CSS.
I've tryed to look to the JWplayer API, but since its terribly unclear to me, over the fact that its partialy in flash, it woudl be simpler if there was a way to trigger it after, or maybe just triggering it after i hover over the body, since every sites has a body. It cant be specific to one page.
Use something like this
var timer;
function injectYouTube() {
// DO YOUR STUFF HERE
// ONCE DONE CALL clearInterval(timer);
clearInterval(timer);
}
timer = setInterval(injectYouTube, 2000);
I am not saying this will be called after everything is loaded but instead you can make sure your code is executed when you want it to.
The JWPlayer API are not that difficult. You can retrive the informations you need even not knowing the container id.
This is an example:
var player = jwplayer(0); // get the first jwplayer element of the page
var video = player.getPlaylistItem(); // get the player video
var url = video.file // retrieve the video url
I think the setTimeout or setInterval are unreliable.
Setting up a listener on jwplayer onReady event would be better.
The pessimistic answer to this is that you can't wait until a page has finished all AJAX operations etc. because web pages can continue loading new content indefinitely if they wish.
What you might consider is running your code every time a new HTML element is added to the page. This way, you can be certain to catch JWPlayer the moment it is inserted into the page.
document.addEventListener("DOMNodeInserted", yourRemovalFunction);

reload php page with javascript

I have drawn a chess board in a php page. Every piece is set as draggable, and every tile as droppable. Once a piece is dropped on a tile, I'd like to reload the php page so the board can be drawn anew along with new positions.
How can I do that: reloading the php page with javascript, without displaying a window asking for confirmation such as "To display this page, Firefox must send information that will repeat any action (such as a search or order confirmation) that was performed earlier. ->Cancel; Resend" ?
Or perhaps there are better solutions?
If you want to avoid having refresh reporting data (for any reason, including the user clicking the reload button) then use the POST-REDIRECT-GET pattern (http://en.wikipedia.org/wiki/Post/Redirect/Get). Read that, it will explain what to do.
Quick solution: you could try:
window.location.reload(true); //true sets request type to GET
Use GET, instead of POST and the dialog box you are getting will go away.
Good luck!
Make use of
window.location.reload();
will refresh automatically
<script>
var timer = null;
function auto_reload()
{
window.location = 'http://domain.com/page.php'; //your page location
}
</script>
<!-- Reload page every 10 seconds. -->
<body onload="timer = setTimeout('auto_reload()',10000);">
reference http://davidwalsh.name/automatically-refresh-page-javascript-meta-tags

Chrome Extension Javascript/jQuery load page and check if changed

I'm looking for a way to load a website and then check after 1 min or so whether the content has changed, if not, repeat. This is because the website I'm trying to get content from contains javascript for loading the div I need. I thought of using some kind of iFrame, but I have no idea where to start and Google isn't helping me.
Edit
This is the code I'm running with atm and scrapUrl is a defined url so don't worry about it:
var iframe = document.body.appendChild(document.createElement('iframe'));
iframe.src = scrapUrl;
$(iframe).ready(function() {
$(iframe).load(function() {
alert('loaded');
alert($(iframe).contents().find('div#description').html());
});
});
It outputs "loaded" and after that "undefined"
So you're doing a lazy load of content in a div, and you want to know when that div has loaded? Depending how you're doing it, you'd be better to set a flag and react to the AJAX "load" event associated with that lazy load.
If you must do it the way you suggest, try this:
Create an interval (setInterval) that checks the load status, or the contents of the div
if false, do nothing. If true, clearInterval.

Click count possible with javascript?

Let's say, in website, I want to display the notice message block whenever people click any of the link at my website more than x number of times. Is that possible to count with javascript and display the notice message block ? And can we count the refresh times also ? Or can it be only done with server side language like php ? Please kindly suggest. Thank you.
With Regards,
To do something when any link is clicked is best done with JQuery's live:
Description: Attach a handler to the
event for all elements which match the
current selector, now and in the
future.
$('a').live('click', function() {
// Live handler called.
});
Even if you add more links in run time, this will take care of it.
For counting refreshes I would do it with ajax calls on window.load event, or if you want to use new tech - store it locally with Html5. :-)
You can do that on the client. However, this will be limited to the browser. The simplest will be to store this information in cookies on the client. For instance with jQuery you could simply intercept clicks like that:
$("a").click(function() {
var clickedUrl = $(this).attr('href');
// Here you update the cookie for the count of clicks for that A URL
});
I would either count page refreshes serverside or probably call an ajax function to update the count when the page loads.
If you want to count clicks you may need to bind an event to each link and then for each indivisual button store the number of clicks in global variables...
You could register each click event on the document by using:
$(document).click(function()
{
// Check the number in the cookie and add another
// click to the cookie
});
Then you could use the jQuery cookie plugin to store that value and check it each time there is a click (in the function above).
here's the cookie plugin: https://github.com/carhartl/jquery-cookie
I threw together a quick example. If you're not worried about doing this from page to page then you don't need cookies, just store it in a variable:
http://www.webdesignandseo.net/jquery/clickcount/

onHashChange running onLoad... awkward

So I'd like my page to load content if a window's hash has changed.
Using Mootools, this is pretty easy:
$extend(Element.NativeEvents, {
hashchange: 1
});
and then:
window.addEvent('hashchange', function() {});
However, the hashchange event is firing when the page is being loaded, even though the specification require it not to fire until the page load is complete!
Unless I am loading the page for the first time, with no hash, then all works as expected.
I think the problem here is the fact that the browser considers the page load "complete", and then runs the rest of the JavaScript, which includes hash detection to load the requisite page.
For example, if I typed in http://foo.bar/, all would work fine. However, http://foo.bar/#test would, ideally, load the initial page, detect the hash, and load the "test" content.
Unfortunately, the browser loads the initial page, considers it "domready", and THEN loads the "test" content, which would then fire onHashChange. Oops?
This causes an infinite loop, unless I specifically ask the browser NOT to update the hash if an onHashChange event is firing. That's easy:
var noHashChange;
noHashChange = true;
var hashes = window.location.hash.substr(1).split("/"); // Deciphers the hash, in this case, hashes[0] is "test"
selectContent(hashes[0]); // Here, selectContent would read noHashChange, and wouldn't update the hash
noHashChange = false;
So now, updating the hash AFTER the page has loaded will work properly. Except it still goes nuts on an initial page load and fetches the content about 3 or 4 times, because it keeps detecting the hash has changed. Messy.
I think it may have something to do with how I am setting the hash, but I can't think of a better way to do so except:
window.location.hash = foobar;
... inside of a function that is run whenever new content is selected.
Therein lies the problem, yes? The page is loaded, THEN the content is loaded (if there is content)...
I hope I've been coherent...
Perhaps you could check the hash first to eliminate the recursion:
if(window.location.hash != foobar){ window.location.hash = foobar;}
Why is the onHashChange handler changing the hash anyways? If there's some default that it's selecting first before loading the content, then perhaps that could go in a seperate function.
(I say this because it looks like you've some sort of directory structure-esque convention to your location.hash'es, perhaps you're selecting a specific leaf of a tree when the root is selected or something?)
you could implement an observer for the hash object that will trigger a function when the has object has changed.it does nothing to do with the actual loading of the page.
the best way to do this is via Object.prototype.watch
see other pages on same topic : On - window.location.hash - Change?
have a look at MooTools History it implements the onhashchange if the new html5 history api isn't available, no need to reinvent the wheel :)

Categories

Resources