Script to load random page on page load/refresh? - javascript

I'm looking for something that will allow me to have a page in the root directory randomly selected to load each time the page is first loaded and with subsequent reloads/refreshes.. I have an index.html and index2.html for example slightly different from each other in the root directory.
I have tried teh Googles but can't find anything / everything I have tried isn't working.
The javascript I'm currently trying try to use is:
var howMany = 3; // number of pages below, count them.
howMany = howMany-1
var page = new Array(howMany+1);
page[0]="index.html";
page[1]="index2.html";
page[2]="index.html";
function rndnumber(){
var randscript = -1;
while (randscript < 0 || randscript > howMany || isNaN(randscript)){
randscript = parseInt(Math.random()*(howMany+1));
}
return randscript;
}
quo = rndnumber();
quox = page[quo];
location.href=(quox);
If I test it locally it seems like it works but it gets stuck in an infinite and automatically reloading/refreshing loop for some reason. When I upload it to server there's no reloading loop but the randomization doesn't work, it just loads the index.html
I have a set up a test page here: http://www.samnorris.co.nz/test2/ which has both the index.html and index2.html in the root directory
Can anyone offer any clue why this might not be working properly and/or a better solution?
thanks!

The javascript is executed on the client on page load. So everytime you load the page, it randomly selects a page and redirects to that page. That page then has some JavaScript emebedded that when executed, selects a random page and loads that, ...
a better solution would be to handle the serving of the page on the server using a server side language. PHP for instance. The code would be something like this:
index.php
<?php
$randNumber = mt_rand(1,3);
if ( $randNumber == 1 )
{
include 'index_1.html';
}
else
{
include 'index_2.html';
}

You have to, somehow, tell the script it has been already redirected. This could be probably achieved using location's hash:
if (location.hash === "#redirected") {
location.hash = "";
}
else {
quo = rndnumber();
quox = page[quo];
location.href=(quox) + "#redirected";
}

Create separate html file with the following content in the same dir as your "index*.html" files:
<script type="text/javascript">
var pages = [
"index.html",
"index2.html",
"index3.html"
];
function randomPage() {
return pages[Math.round(Math.random() * (pages.length - 1))];
}
location.href= randomPage();
</script>

Related

Browser does not replace an include file by its including file

I am an absolute beginner in JS.
1) What I'm trying to do:
My web pages are composed of an index.php which is the same for all the files of a directory and one of a set of content.inc, like this: index.php?open=content.inc. This is done by a PHP snippet in the index.php and works well.
However, Google indexes all the content.inc files. The user's browser then displays the content.inc without the framing index.php. This I want to avoid. I therefore add a modest script at the beginning of each content.inc (which I would convert into a function once it runs) to tell the browser that instead of displaying the content.inc, it should display index.php?open=content.inc.
2) My unworkable solution:
var url = window.location.pathname;
var filename = url.substring(url.lastIndexOf('/')+1);
if (filename.indexOf("index.php") = -1)
{ var frame_name = "index.php?open="+filename;
window.location.replace(frame_name);
};
The browser (Firefox 60) ignores this; it displays content.inc. (I also have versions of this script which get the browser into an endless loop.)
What is wrong here? Please help!
PS: Please be assured that I have done extensive web search on this problem and found many pages of complaints about location.replace getting into an infinite loop; but none matches my situation. However, I gratefully accept a helpful link as an answer.
For starters, you have an error in this line:
if (filename.indexOf("index.php") = -1)
That's an assignment and will always evaluate to true, you need to use == or === (which should be more performant).
The guilty line is on your test case (see JP de la Torre answer). And to improve, here's a snippet to demo how to analyze the url with a regular expression :
function redirect(url) {
if(url && url.indexOf('.inc') >= 0) {
return url.replace(/\/(\w+)\.inc/, '/index.php?open=$1');
}
return url;
}
let urls = [
window.location.href,
'http://google.fr',
'http://example.com/index.php?open=wazaa',
'http://example.com/wazza.inc'
];
urls.forEach(url => {
console.log(url, ' => ', redirect(url));
});
The regexp will capture any text between a / and .inc. You can use it then as replacement value with the $1.
And applied to your case, you simply need :
if(window.location.href.indexOf('.inc') >= 0) {
window.location.href = window.location.href.replace(/\/(\w+)\.inc/, '/index.php?open=$1');
}
You can also use .htaccess server side to redirect request for .inc files on your index.php if mod_rewrite is enabled.
The solution to the problem of including an INC file called separately is the one proposed by Bertrand in his second code snippet above. It presupposes (correctly) that the inc extension is omitted in the replacement.
As I reported above, Firefox may get into an endless loop if it opens a PHP file directly, i.e. without involving the local host (with its php module).

Why isn't my if statement executing correctly even though condition has been met?

This is an InDesign script to convert indd files into jpgs and then export and rename them into a folder on my desktop. It all works fine, but there is one part that I'm trying to do, which is only export the pages that do not have the Master Page "H-Advertising" applied. I've written an if statement that checks what master page has been applied to the current page of the current document and should ostensibly only export that page if it hasn't had "H-Advertising" applied as a master page. I know that the loop works if I add a different condition (such as if (3!=4)) and it is also able to alert the master page of each page, but it just seems to go ahead and add the page to the array of pages I want to export no matter what.
Main();
function Main() {
// Check to see whether any InDesign documents are open.
// If no documents are open, display an error message.
if (app.documents.length > 0) {
app.jpegExportPreferences.exportingSpread = false;
//makes sure there is a book open
if (app.books.length != 1)
alert("This only works when you have one (1) book open and the first file in that book open");
else
//loop through the book's stories
for (b = 0; b < app.books[0].bookContents.length; b++) {
// initialize pages variable
var pages = [];
// loop through the pages in the active document
for (i = 0; i < app.activeDocument.pages.length; i++) {
// initialize variable holding document name, and then rename as follows
var myDocumentName = app.books[0].bookContents[b].fullName;
c = app.open(app.books[0].bookContents[b].fullName);
myDocumentName = myDocumentName.name.replace("indd", "jpg");
myDocumentName = myDocumentName.replace("WN16", "WN16_");
// get value of the current page's applied master
if (app.activeDocument.pages[i].appliedMaster != null) {
var appliedMaster = app.activeDocument.pages[i].appliedMaster.name;
}
// if it's not an advertising page, get the page number and add it to an array containing page numbers to export
if (appliedMaster !== "H-ADVERTISING" && appliedMaster!= "[None]" && appliedMaster!= null) {
alert(appliedMaster);
pages.push(app.activeDocument.pages[i].name);
printpages = pages.join(",");
// set the pageString of pages to export as jpegs
app.jpegExportPreferences.pageString = printpages;
// export all the pages using the export page range page string
c.exportFile(ExportFormat.JPG, File(Folder.desktop + "/EDIT_Jpgs/" + myDocumentName));
}
}
};
Note: Property 'pageString" is valid when JPEG export range is not all. So - just to be sure - you may need to set app.jpegExportPreferences.jpegExportRange to 'ExportRangeOrAllPages.EXPORT_RANGE'
Note2: Consider that a book could be opened without opened docs OR an activeDocument could be from outside of app.books[0] ==> in this case your loop for (i = 0; i < app.activeDocument.pages.length; i++) possibly lead to wrong values, cause target doc is opened... inside this loop.
Jarek
Okay, the script is working now, after I updated to InDesign 2017. So, not really an answer, other than there must have been a bug in InDesign. The only thing I did tweak in the code was to add this
if (app.activeDocument.pages[i].appliedMaster !== null && app.activeDocument.pages[i].appliedMaster!== "H-ADVERTISING" && app.activeDocument.pages[i].appliedMaster!==null) {
appliedMaster = app.activeDocument.pages[i].appliedMaster.name;
}
earlier in the code which checked the actual value of the master page, instead of checking a variable that was assigned the value of the master page. This seemed to be the trick to checking to filter for any pages that had no master page applied (null or "[None]")

Is it possible to disable a javascript IF statement for a specific page

A javascript with "IF" statement written in all pages header template and which is unnecessary only for a specific page, is it possible to disable that statement for a specific page. Below is the javascript which make external links to open in new tab, can i disable this small script only for a google custom search page because the result links have google(external) url which redirects to website(internal), that's why script is reading links as external. Or is there some better way than disabling the if statement? If anyone knows how to solve this problem, please help
Javascript:
$(document).ready(function() {
$('a').each(function() {
var a = new RegExp('/' + window.location.host + '/');
if (!a.test(this.href)) {
$(this).attr("target", "_blank");
}
});
});
One way to do it for multiple pages, like this:
var excludedPages = ['blockpage1.html', 'blockpage2.html'];
for (var i = 0; i < excludedPages.length; i++) {
if (location.href.indexOf(excludedPages[i]) !== -1) {
// do something if page found
console.log("this page is blocked for extra code");
} else {
// do something if page not found in the list
console.log("this page is not included in block list");
}
}
EDIT
Note: The only thing to be aware of with JavaScript, it is running on client side (browser side) and any one with basic web development knowledge are able to change the block site or edit any the site content. This make it possible getting access to what ever site that was blocked. So it all depends how important your blocking mechanism and strategy.
Probably the easiest way would be to set a flag variable on the custom search page above the script, for example:
var keepInternal = true;
And then modify one line in your script to check for that flag:
$(document).ready(function() {
$('a').each(function() {
var a = new RegExp('/' + window.location.host + '/');
if (!a.test(this.href) && !keepInternal) {
$(this).attr("target", "_blank");
}
});
});

Reload updated java<script> code without fully reloading the html page

I am developing a single page web application, that has many different features and forms. When developing a deep (I mean something that is not on the home page) feature, I go through this cycle:
develop the code, editing classes and functions
refresh the whole page
clicking all the way till I get to the part that I need to test (that adds up to about a minute sometimes)
testing the new code
back to the (1) code editor doing updates
doing about 15 minor edits, can take a frustrating 30 minutes of repeated reloading and clicking
Is there any plugin, piece of javascript, or method, that allows to reload the updated javascript without reloading everything, so one can skip the 2. and 3. from the cycle above and continue doing live tests?
If there's no such thing, I am planning on developing a little javascript plugin that will reload the scripts, and probably with socket.io connection to a backend node.js server that will watch the files for any updates and push the load events to the browser.
So, I am interested in any idea about this, any thing that I should take into consideration when writing the plugin.
Thanks : )
You could do something like this.
function LoadMyJs(scriptName) {
var docHeadObj = document.getElementsByTagName("head")[0];
var dynamicScript = document.createElement("script");
dynamicScript.type = "text/javascript";
dynamicScript.src = scriptName;
docHeadObj.appendChild(newScript);
}
Call the LoadMyJs function on page load
<body onLoad="LoadMyJs()">
Then reload with the click of a button (or from your console)
<input type="button" name="reloadjs" value="Reload JavaScript" onclick="LoadMyJs('my_live_loading_script.js')">
This could be simplified using e.g jQuery
Thanks to:
http://www.philnicholas.com/2009/05/11/reloading-your-javascript-without-reloading-your-page/
Here's what I came up with: a Node.js module that watches for changes in .js & .coffee scripts, and pushes the changes to the browser upon editing the files.
It works standalone, even if you are developing on filesystem file:/// without using a web server.
It works with any framework, just launch the standalone script and point it to your js/ directory.
It has an express.js helper, that make it run using the same server instance.
It is as easy as
adding a single line of <script> tag to your existing code, and
running the live script, pointing it to the html root.
code: 🐱/etabits/live.js
That's may be not the best answer but for local developments I use that firefox plugins:
https://addons.mozilla.org/en-US/firefox/addon/auto-reload/
This reload the css, js or anything present in a directory
For dev which really needs to be remotely , I use that small js code you can adapt for reloading js.
function refreshCss(rule){
if (rule == null)
rule = /.*/;
var links = document.getElementsByTagName("link");
for(var i=0;i<links.length;i++)
{
if (!links[i].href.match(rule))
continue;
if (! links[i].href.match(/(.*)time=/)){
if (links[i].href.match(/\?/))
var glue = '&';
else
var glue = '?';
links[i].href += glue+"time="+new Date().getTime();
}
else{
links[i].href.replace(/time=\d+/, "time"+new Date().getTime());
}
}
if (!no_refresh)
{
setTimeout(function(){refreshCss(rule)}, 5000);
}
};
// and then call it refreshCss("regex to match your css, or not"); var no_refresh=false;
Edit: this is a version with "setTimeout", but you can easily made a "keypress" version of it
Replace with dynamic script.
function LoadMyJs(scriptName)
{
var docHeadObj = document.getElementsByTagName("head")[0];
var dynamicScript = document.createElement("script");
dynamicScript.type = "text/javascript";
dynamicScript.src = scriptName;
docHeadObj.appendChild(dynamicScript);
}

Navigating / scraping hashbang links with javascript (phantomjs)

I'm trying to download the HTML of a website that is almost entirely generated by JavaScript. So, I need to simulate browser access and have been playing around with PhantomJS. Problem is, the site uses hashbang URLs and I can't seem to get PhantomJS to process the hashbang -- it just keeps calling up the homepage.
The site is http://www.regulations.gov. The default takes you to #!home. I've tried using the following code (from here) to try and process different hashbangs.
if (phantom.state.length === 0) {
if (phantom.args.length === 0) {
console.log('Usage: loadreg_1.js <some hash>');
phantom.exit();
}
var address = 'http://www.regulations.gov/';
console.log(address);
phantom.state = Date.now().toString();
phantom.open(address);
} else {
var hash = phantom.args[0];
document.location = hash;
console.log(document.location.hash);
var elapsed = Date.now() - new Date().setTime(phantom.state);
if (phantom.loadStatus === 'success') {
if (!first_time) {
var first_time = true;
if (!document.addEventListener) {
console.log('Not SUPPORTED!');
}
phantom.render('result.png');
var markup = document.documentElement.innerHTML;
console.log(markup);
phantom.exit();
}
} else {
console.log('FAIL to load the address');
phantom.exit();
}
}
This code produces the correct hashbang (for instance, I can set the hash to '#!contactus') but it doesn't dynamically generate any different HTML--just the default page. It does, however, correctly output that has when I call document.location.hash.
I've also tried to set the initial address to the hashbang, but then the script just hangs and doesn't do anything. For example, if I set the url to http://www.regulations.gov/#!searchResults;rpp=10;po=0 the script just hangs after printing the address to the terminal and nothing ever happens.
The issue here is that the content of the page loads asynchronously, but you're expecting it to be available as soon as the page is loaded.
In order to scrape a page that loads content asynchronously, you need to wait to scrape until the content you're interested in has been loaded. Depending on the page, there might be different ways of checking, but the easiest is just to check at regular intervals for something you expect to see, until you find it.
The trick here is figuring out what to look for - you need something that won't be present on the page until your desired content has been loaded. In this case, the easiest option I found for top-level pages is to manually input the H1 tags you expect to see on each page, keying them to the hash:
var titleMap = {
'#!contactUs': 'Contact Us',
'#!aboutUs': 'About Us'
// etc for the other pages
};
Then in your success block, you can set a recurring timeout to look for the title you want in an h1 tag. When it shows up, you know you can render the page:
if (phantom.loadStatus === 'success') {
// set a recurring timeout for 300 milliseconds
var timeoutId = window.setInterval(function () {
// check for title element you expect to see
var h1s = document.querySelectorAll('h1');
if (h1s) {
// h1s is a node list, not an array, hence the
// weird syntax here
Array.prototype.forEach.call(h1s, function(h1) {
if (h1.textContent.trim() === titleMap[hash]) {
// we found it!
console.log('Found H1: ' + h1.textContent.trim());
phantom.render('result.png');
console.log("Rendered image.");
// stop the cycle
window.clearInterval(timeoutId);
phantom.exit();
}
});
console.log('Found H1 tags, but not ' + titleMap[hash]);
}
console.log('No H1 tags found.');
}, 300);
}
The above code works for me. But it won't work if you need to scrape search results - you'll need to figure out an identifying element or bit of text that you can look for without having to know the title ahead of time.
Edit: Also, it looks like the newest version of PhantomJS now triggers an onResourceReceived event when it gets new data. I haven't looked into this, but you might be able to bind a listener to this event to achieve the same effect.

Categories

Resources