Basically I'm trying to scrape a few divs out of several of the intranet sites at work. and include them on a page I run locally (so I can look at one page instead of having 5 open). I'm guessing this is possible with JavaScript but I'm primitive with JavaScript so I'm not sure what I need to search for to find the answers. After I scrape the Div's from these other pages I want to add a refresh timer with something like setInterval()
This task is not as difficult as it should be, thanks to the glorious jQuery library...
$(document).ready(function() {
// Repeat this for each of your URLs
$.get("URL", function(data) {
var resp = $(data); // Now you can do whatever you want with it
$("#ID_OF_DIV", resp).appendTo("body");
});
// End Repeat
setTimeout(function() {
location.reload(true);
}, 10000); // Refresh every ten seconds
});
You can to access those external pages using an XMLHttpRequest object, grab it's HTML source and strip just that information you want.
maybe this link can be useful: Auto refresh <DIV> using ajax
Related
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.
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);
So I've made a web app, image below. The app has several tabs which contain different information such as graphs and indicators. The app is made using HTML & Javascript and is one document. I have implemented a Javascript timer which, every 60 seconds, loads the exact same webapp but in a different HTML document, just with different values for the graphs etc. This was just to make it easy for me as i don't have a lot of time at the moment. So every minute the web apps graphs will refresh with different data coming from a different document. So basically i have index.html, index2.html and index3.html, all with the same code/webapp but loading different values into the graphs. Heres the code for the timer:
<script type="text/javascript">
var myVar=setInterval(function(){myTimer()},60000);
$(function () {
});
function myTimer()
{
window.location.replace("index2.html");
}
</script>
The only problem with this is that when, for example, index.html reaches 60 seconds and loads index2.html it goes back to the very first tab (Summary), is there anyway to remain on the same tab even though it's loading a different document?
As #JoshuaM pointed out, the best solution would be to use AJAX, but since you seem mostly satisfied with your current method, you could use a hash on the URL to indicate which tab should be active, e.g.:
index.html#/metrics
index2.html#/metrics
etc...
(I like to put in a leading slash for this sort of thing to distinguish it from a regular anchor link or unexpectedly jumping to an element with the same ID, but in a simple case like this, index.html#metrics could work just as well).
The link for the metrics tab would look like this:
Metrics
(Keep whatever Javascript you have set up on it to make the tabs work.)
Then, when loading the next page, append the hash to it:
var nextPage = 'index2.html';
window.location = nextPage + window.location.hash;
Finally, check for the hash when first loading a page:
var hash = window.location.hash;
//hashes indicating which tab to make active should begin with a slash, e.g. #/metrics
if (hash[1]=='/') {
var currentTab = hash.substr(2);
//activate current tab...
}
Another alternative would be to use an iframe for the graph content but that would probably require more reworking of your code.
I want to autorefresh a div on this page: http://americanart.si.edu/index_newsplash3r.cfm ("Places to Explore" area). Right now we have 3 different images and text that arbitrarily display when you reload the page. I'd like these elements to change automatically, without reloading the page.
The page is done in Coldfusion 9. Most AJAX autorefresh code assumes you're using PHP.
Does anyone have a link to code I could use to do this without PHP? I don't think it's necessary that it be Coldfusion code.
Thanks.
You can setup an Ajax call to the server side to get the photo path and the text.
Something like this.
$(function(){
function FillDivAtRandom(current){
setTimeout(function(){
//pass the current place to explore id to the server so you don't get the same back, if none then return anyone.
$.post("http://americanart.si.edu/Request/PlacesToExploreNext", current, function(data){
//fill the div with new data return from server
//you don't seem to have an ID on that div or elements so put one on it first then use it as a selector
//set the image
$('#placestoexplore_image').attr('src', data.image);
//set the text
$('#placestoexplore_description').html(data.description);
});
//call the function again
FillDivAtRandom(current);
}, 10000);
}
}
I have index.php and images.php. And what I want is that a certain div on index.php is getting it's content from images.php automatically and refresh when new content is present on images.php. I currently have this:
$(document).ready(function() {
$.ajaxSetup({ cache: false });
setInterval(function() {
$('#images').load('images.php');
}, 500);
});
This works fine, but it refreshes the div every .5s which I don't want, I want it to detect when new content has been inserted into images.php then load it in.
But the thing is, on images.php I have some timestamps (1 minute ago, etc.). And jQuery will detect those as changes and will then refresh.
Is there a way to count the number of image tags (<img>) on the images.php page and compare them with the number of image tags in the div on the index.php page, and then if they are not equal, refresh the div on index.php.
The short answer is - no.
You should understand, that there's server side of your code and client side. Whenever browser sends a request, it gets a formatted html page (not a php script to execute) and gets all embedded resources (images, css, js files etc).
After that no communication is done between the client (browser) and a server (your web server). For you to get updated 'images.php' page you'd need to send a notification from a server to all browsers looking at your page currently (which you don't know - you'd need a fixed connection with them, but html protocol is stateless meaning there's no easy way of accomplishing it).
So, the easiest way is to have browser ping server in a timely fashion - every n seconds. Though, it would probably be better to fetch not all images every n seconds, but the last change date - and have some logic to fetch new data when it has a newer change date - this would reduce amount of traffic sent by your application.
var imageWrapper = $('#images'),
imageCount = $imageWrapper.find('img').length;
setInterval(function() {
$.get('images.php', function (html) {
html = $(html);
if ( html.find('img').length > imageCount ) {
$imageWrapper.html( html );
}
});
}, 500);