Sorry if this is a simple question (or answered before), but could anyone tell me how to download a page with JScript? I want to use Javascript to download the page "example.php" on my server every five seconds and compare it with what it was before. If the page changes, I would like the Javascript code to refresh the page hosting the Javascript. Does that make sense ? Somethingl ike:
string downloaded = DownloadPage("example.php");
timer x = new timer(5);
when the timer goes off:
if(DownloadPage("example.php") == downloaded){
RefreshPage();
}
Thanks, and sorry this was probably such an easy question :)
Using the jQuery framework's get function:
$.get('example', function(data) {
if(data == "something")
//perform action
});
Related
I'm trying to make a website load forever. My current idea is to request a PHP file:
<?php
sleep(30);
This will delay the load by 30 seconds, which a quick Google search tells me should be within most browsers' timeouts. I was thinking of writing some JavaScript to append a new link tag after a bit less than 30 seconds to keep the page loading, but I found that this didn't keep the loading icon spinning (with Chrome at least):
window.addEventListener( 'load', () => {
var i = 0;
setInterval( () => {
i++;
var newScript = document.createElement('script');
newScript.src = 'infinite-loading.php?i=' + i;
document.querySelector('#infinite-loading').after(newScript);
console.log('The deed is done');
}, 25000)
} )
<script id="infinite-loading" src="infinite-loading.php"></script>
The code above appends a script tag every 25 seconds, and the browser loads the PHP file each time, but it doesn't show the loading icon. I added the URL parameter because I wasn't sure if browsers would cache the page.
I also want to make sure that the server with the PHP file won't be overloaded. I'm not sure if many sleep() functions running constantly at the same time will cause any issues.
Is there a better way to do this client-side? Should I use something other than PHP? Something multi-threaded?
(Edit: Sorry for the awkward title, Stack Overflow didn't like my first one.)
You need that browser will continue reading your page forever (I'm talking about HTML, not other linked objects). So you need not to break timeout and feed some data from backend to frontend.
Example of sending portion of data to client:
ob_end_flush();
# CODE THAT NEEDS IMMEDIATE FLUSHING
ob_start();
Now we need to understand the minimum data packet size that is expected by the browser. Minimal googling tells us a limit of 8-10 bytes.
So combining this together we can try to check (I did not checked, it is just my version):
<?php
while (true) {
sleep(25);
ob_end_flush();
echo " "; // 10 spaces...
ob_start();
}
Not sure why you would want to do anything like this but the simplest solution I think is an endless loop.
<?php
while(true)
{
}
This question already has an answer here:
How can I have a Tampermonkey userscript play a sound when a specific word appears on a page?
(1 answer)
Closed 4 years ago.
I want to monitor a website word changes. I am looking for a sound to autoplay when a given word appears on the screen.
This word might come embedded within a new div ID, so I am not monitoring a particular DOM object change, but a string/new-word that appears on the screen eventually.
In short, I am looking for a JS that plays a sound everytime the word "Customer" appears on the screen. I have tried this code (copy paste from someone else) so far and it plays a sound everytime the page reloads, but not when the word "Customer" appears on the screen.
HereĀ“s the code:
var player = document.createElement('audio');
player.src = 'https://dl.dropbox.com/u/7079101/coin.mp3';
player.preload = 'auto';
for (var i = 0; i <= 10; i++) {
if (i === 10) {
// Play a sound when i === 10
player.play();
} else {
console.log('Not yet!');
}
}
Of course this is just a piece of code that checks for something very different, but when fiddling around with it, I find that everytime I modify the formula it stops playing the sound on tab reload.
Let me start off by saying more info is required (see my comments above), and you should try and make an effort to first get some stub of code together that actually does/attempts to do what you're trying to achieve. StackOverflow is not some kind of code-requesting forum where you can ask others to write something for you.
Since you're new here, I'll try to get you started with some ideas:
It's still unclear to me whether you're trying to scan through a page 'of your own' (i.e. on your own server), or someone else's page (on another server).
Scanning the same page (on your server) that your javascript code is on
If you're scanning one of your own pages, and you can even run the javascript on that very page, your solution will be very simple (source: Javascript: how to check if a text exists in a web page ). I personally prefer the jQuery solution posted in this question:
var player = document.createElement('audio');
player.src = 'https://dl.dropbox.com/u/7079101/coin.mp3';
player.preload = 'auto';
window.setInterval(function(){
if($("*:contains('Customer')").length > 0){
console.log('Customer detected, playing sound...');
player.play();
}
}, 5000);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Customer!
There is of course still he problem that you'll probably only want to play the sound once for every new occurance of the word 'customer'. This will require more advanced programming (you'll have to keep track of which words you've already played the sound for), which is kind of out of scope for this question.
Scanning a different page (on your server, or an external one*)
If you're loading a different HTML page (or other text-type page, doesn't really matter) you can also find your solution on StackOverflow (source: How to check if string exists on external page with JavsScript? ). In short, you'll perform an AJAX request to get the page, and then check for the word 'Customer'. *The same-origin policy will however prevent you from loading most external pages purely through javascript (read more: Loading cross domain endpoint with jQuery AJAX ), so you will need some kind of cross-origin plugin (read more in this topic).
var player = document.createElement('audio');
player.src = 'https://dl.dropbox.com/u/7079101/coin.mp3';
player.preload = 'auto';
var url= 'http://www.businessdictionary.com/definition/customer.html';
window.setInterval(function(){
$.get(url, function(data) {
if(data.indexOf('whatever') != -1) {
console.log('Customer detected, playing sound...');
player.play();
}
}, 'text');
}, 5000);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Best of luck with your project, and welcome to StackOverflow. I will update my answer if needed, or when you provide more information.
I want to catch the browser back button before any thing happened to page. I have looked into many solutions, some catch this event when the previous page is loaded fully, I don't need that. I need to catch it before even any thing happen.
I found another good solution,
$(window).on('popstate', function() {
var hashLocation = location.hash;
var hashSplit = hashLocation.split("#!/");
var hashName = hashSplit[1];
if (hashName !== '') {
var hash = window.location.hash;
if (hash === '') {
alert('Back button was pressed.');
}
}
});
window.history.pushState('forward', null, '#b');
}
Quite effective solution, this catch back button event before even anything happened to the page but this write #b with my URL, which is not acceptable.
Need help, to catch any browser back button, before even any thing happen to the page.
Actually, my complete story is, When back is pressed i store a variable in cookie. Soon script is first hit on page load, i check cookie, theni reload the whole page. So that a server side is call generated instead of cache. Any alternative solution?
I am looking for a solution for a quite long time, but no effective solution found yet.
Thanks in advance.
Finally i found solution for i was looking for. I need to handle back button because i don't want to load page from cache. I cannot stop caching, because i want my browser to cache CSS and jquery, but not html. stop caching only HTML is not possible so far i think. So i found a solution, I add a cookie in my server side, RequestedFrmServer. Set it 1 each time my code at server is hit (or when server side request is generated), soon my client side script is hit, i set it back 0 only. I placed a condition, if the value is 0 then reload the whole page. here is the code.
var _historyBack = $.cookie('RequestedFrmServer');
if (_historyBack != undefined && _historyBack == "1")
{
setCookie("RequestedFrmServer", "0");
}
else if(_historyBack != undefined && _historyBack == "0")
{
window.location.reload(true);
}
worked in my case. If work for you, i deserve a thumb up. :)
This question already has answers here:
Sequencing ajax requests
(10 answers)
Closed 7 years ago.
I'm working on a small text game in js, and the easiest way I found to have save text is to use text files. I can order them in different folders, they really light and they're easily identifiable and editable in case I need to make changes.
I'm loading them using ajax
$.ajax({
url: 'text/example.txt',
success: function(text){
document.getElementById("main").innerHTML = document.getElementById("main").innerHTML + text;
}
});
As it was suggested to me in another thread.
And honestly, so far it's been working pretty well, in single-cases scenarios. When only one TXT file needs to be displayed there are literally no problems. But, unfortunately in cases where a lot of different files need to be displayed in a correct order (let's say around 10 different files), the text gets messed up and loads out of order. I'm going to suppose this is because it just can't fetch the txt file fast enough.
So at this point I'm really not too sure what to do.
Is there a way to get my script to wait before printing the next piece of text before displaying one that still hasn't loaded?
Maybe a way to load all the txt files when the site is accessed?
My knowledge is pretty limited so I'm really not sure how this could be fixed.
Tried searching google and stackoverflow, none of the threads I found are helping me, perhaps because I'm really not an expert.
You can achieve with callback, the following way will call ajax one by one after they finish:
//setup an array of AJAX url
var ajaxes = [{ url : 'text/example.txt'}, { url : 'text/example1.txt'}],
current = 0;
//declare your function to run AJAX requests
function do_ajax() {
//check to make sure there are more requests to make
if (current < ajaxes.length) {
//make the AJAX request with the given data from the `ajaxes` array of objects
$.ajax({
url : ajaxes[current].url,
success : function (text) {
document.getElementById("main").innerHTML = document.getElementById("main").innerHTML + text;
//increment the `current` counter and recursively call this function again
current++;
do_ajax();
}
});
}
}
//run the AJAX function for the first time when you want
do_ajax();
I'm currently programming in JSP and Javascript. (I am by no means an expert in either). Right now, what I want is for a Javascript function to be called repeatedly and one of the variables to be queried from the database repeatedly (it is the date that the page was last modified). If this variable is greater than when the page was loaded, I want the page to refresh.
What I have so far:
...
<body onload="Javascript:refreshMethod()">
<script type="text/JavaScript">
<!--
function refreshMethod()
{
var interval = setInterval("timedRefresh()", 10000);
}
function timedRefresh() {
var currenttime = '<%=currentTime%>';
var feedlastmodified = '<%=EventManager.getFeedLastModified(eventID)%>';
var currenttimeint = parseInt(currenttime);
var feedlastmodifiedint = parseInt(feedlastmodified);
if(feedlastmodifiedint > currenttimeint)
{
alert(feedlastmodifiedint);
setTimeout("location.reload(true);",timeoutPeriod);
}
if(feedlastmodifiedint < currenttimeint)
{
alert(feedlastmodifiedint + " : " + currenttimeint);
}
}
// -->
</script>
The problem is that everytime the timedRefresh runs, the feedlastModifiedInt never changes (even if it has been changed).
Any help would be appreciated,
Thanks.
The JSP code within the <% ... %> tags runs only once, on the server-side, when the page is loaded. If you look at the source of the page in the browser, you will find that these values have already been placed within the JavaScript code, and thus they will not change during each timer interval.
To update the data as you are expecting, you can use AJAX. You can find plenty of tutorials online.
JSP and JavaScript doesn't run in sync as you seem to expect from the coding. JSP runs at webserver, produces a bunch of characters which should continue as HTML/CSS/JS and the webserver sends it as a HTTP response to the webbrowser as response to a HTTP request initiated by the webbrowser. Finally HTML/CSS/JS runs at the webbrowser.
If you rightclick the page in webbrowser and choose View Source, you'll probably understand what I mean. There's no single line of Java/JSP code. It has already done its job of generating the HTML/CSS/JS. The only communication way between Java/JSP and JavaScript is HTTP.
You need to move this job to some servlet in the server side and let JS invoke this asynchronously ("in the background"). This is also known as "Ajax". Here's a kickoff example with a little help of jQuery.
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script>
$(document).ready(function() {
var refreshInterval = setInterval(function() {
$.getJSON('refreshServlet', function(refresh) {
if (refresh) {
clearInterval(refreshInterval);
location.reload(true);
}
});
}, 10000);
});
</script>
Where the doGet() method of the servlet which is mapped on an url-pattern of /refreshServlet roughly look like this:
response.setContentType("application/json");
if (EventManager.getFeedLastModified(eventID) > currentTime) {
response.getWriter().write("true");
} else {
response.getWriter().write("false");
}
See also:
Communication between Java/JSP/JSF and JavaScript