If URL = this { //do this } else { //do this } - javascript

I know this may seem simple, I thought so myself when I first tried it, but it turns out i'm having issues with it. This is a Userscript and I am wanting it to check if the URL is "http://orteil.dashnet.org/cookieclicker", then do one thing (but don't refresh) but if the URL is "http://orteil.dashnet.org/cookieclicker/beta" the do this other thing (also don't refresh). Here is the code that I have so far, I am just wanting to get "linkb" to run when "http://orteil.dashnet.org/cookieclicker" and "linkc" to run when "http://orteil.dashnet.org/cookieclicker/beta".
var link = document.createElement('a');
link.setAttribute('href', 'http://orteil.dashnet.org/experiments/cookie/');
link.target = 'blank';
link.appendChild(
document.createTextNode('Cookie Clicker Classic')
);
var add = document.getElementsByTagName('div')[1];
add.insertBefore(document.createTextNode('| '), add.lastChild);
add.insertBefore(link, add.lastChild); // all the code so far will load on both pages
var linkb = document.createElement('a');
linkb.setAttribute('href', 'beta');
linkb.target = 'blank';
linkb.appendChild(
document.createTextNode('Try the beta!') //this block will load if the URL is "http://orteil.dashnet.org/cookieclicker"
var linkc = document.createElement('a');
linkc.setAttribute('href', '../');
linkc.target = 'blank';
linkc.appendChild(
document.createTextNode('Live version') // and this will load if the URL is "http://orteil.dashnet.org/cookieclicker/beta"
I have tried:
if (window.location = "http://ortei.dashnet.org/cookieclicker/") {
var linkb = document.createElement('a');
linkb.setAttribute('href', 'beta');
linkb.target = 'blank';
linkb.appendChild(
document.createTextNode('Try the beta!')
);
}
else {
var linkc = document.createElement('a');
linkc.setAttribute('href', '../');
linkc.target = 'blank';
linkc.appendChild(
document.createTextNode('Live version')
);
}
I have tried this but with alert()'s and when you push ok on the popup, it refreshes the page and does the alert again. I just want it to check what URL it is and do the corresponding code.
If anyone could come up with some ideas, or even possibly a solution, it would be much appreciated.
Thanks, Daniel

Is should be if (window.location == "http://ortei.dashnet.org/cookieclicker/") (double =), otherwise you're assigning the URL to the window.location, thus forcing a reload

Related

Saving text in a Word Document using JavaScript

For a project I need to save some text into a word document. I do this using this function:
function saveText(text) {
var data = new Blob([text], {type: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'});
var textFile = window.URL.createObjectURL(data);
if (document.getElementById('download') !== null) {
document.body.removeChild(document.getElementById('download'));
}
var a = document.createElement("a");
a.setAttribute("id", "download");
a.setAttribute("href", textFile);
a.setAttribute("download", "");
a.textContent = "Click here to download the test for the students";
document.body.appendChild(a);
}
However, there is one problem. Whenever I try to open it it shows this error message:
The file is corrupt and cannot be opened.
(Sorry I couldn't embed the image; I don't have enough reputation yet)
So, I have a feeling that the problem is that I need to format my text differently because right now I am just calling the function like this: saveText("Test");. In an rtf file it does have lots of stuff at the start so I thought maybe word needs this as well. However, I have looked a lot 'round the internet and couldn't find a solution. Thanks for taking the time to read (and maybe answer) this :D
function saveText(text) {
var data = new Blob([text], {type: 'application/msword'});
var textFile = window.URL.createObjectURL(data);
if (document.getElementById('download') !== null) {
document.body.removeChild(document.getElementById('download'));
}
var a = document.createElement("a");
a.setAttribute("id", "download");
a.setAttribute("href", textFile);
a.setAttribute("download", "");
a.textContent = "Click here to download the test for the students";
document.body.appendChild(a);
}
I simply changed application/vnd.openxmlformatsofficedocument.wordprocessingml.document to application/ms-word and everything worked :)

Angularjs/Restangular, how to name file blob for download?

For some reason this seems easier in IE than Chrome/FF:
$scope.download = function() {
Restangular.one(myAPI)
.withHttpConfig({responseType: 'blob'}).customGET().then(function(response) {
//IE10 opens save/open dialog with filename.zip
window.navigator.msSaveOrOpenBlob(response, 'filename.zip');
//Chrome/FF downloads a file with random name
var url = (window.URL || window.webkitURL).createObjectURL(response);
window.location.href = url;
});
};
Is there a way to do something similar to how IE10+ works? That is, I can specify a file name/type (will only be zip)?
As soon as you have your object url you can create an anchor and set the download attribute to the filename you want, set the href to the object url, and then just call click
var myBlob = new Blob(["example"],{type:'text/html'})
var blobURL = (window.URL || window.webkitURL).createObjectURL(myBlob);
var anchor = document.createElement("a");
anchor.download = "myfile.txt";
anchor.href = blobURL;
anchor.click();
Download attribute compatibility
Just use https://www.npmjs.com/package/angular-file-saver
Browser Support table can be seen here: https://github.com/eligrey/FileSaver.js/

Display Image Based on URL Ending (Variable or Attribute) [Pound/Number Sign # ]

I need an image to be displayed based on the ending of a URL.
For example, I need "123.jpg" to be displayed when someone visits:
website.com/view/#123
website.com/view/#123.jpg
website.com/view#123
website.com/view#123.jpg
(whichever is recommended or would actually work)
I'm looking for the end result to be: < img src=123.jpg" >
Thanks in advance. I will sincerely appreciate any assistance.
(By way of background or additional information, I need this for Facebook's sharer.php so that people can share one of hundreds of images on a given webpage (for example, website.com/blog and they happen to love the 123rd image on there), they click the link to share that specific image (123.jpg), and then any of their friends who clicks on the link (website.com/view/#123) will arrive at a themed page with just the image in the middle (123.jpg) and nothing else, and then they can click around the rest of the website. The main benefit is that 123.jpg will be the only image that shows up as a thumbnail on the Facebook Feed or "Wall".)
window.onhashchange = function() {
if (location.hash) {
var url = location.hash.substr(1); // strip the # char
if (url.indexOf('.') == -1) {
url += '.jpg';
}
document.getElementById('myImg').src = url; // show the image; value of the variable 'url'
}
};
window.onhashchange(); // call the event on load
Use something like this.
$(document).ready(function(){
var url = document.URL; //get the url
if ( url.indexOf("#") != -1 ) //check if '#' is present in the url
{
var split_array = url.split("#");
var image_url = split_array[split_array.length - 1];
//display the image
}
});
Try this out,
$(document).ready(function() {
getImageSrc();
$(window).on('hashchange', getImageSrc); // will always lookout for changes in # URL
});
function getImageSrc() {
if(window.location.hash) {
var imgSrc = window.location.hash.substr(1);
if(imgSrc.indexOf('.') == -1 ) {
imgSrc = imgSrc + ".jpg";
}
alert(imgSrc);
}
}

How to switch to generic auto redirect with delay

I've inherited a site that calls a javascript on every page to prepend every external link with a link to an exit page. On exit.html, a function in the same script (confirmExit) extracts the original intended url, and that’s served up as a link on the page by ID (<p>Continue to:</p>)
Now, instead of the user having to click on exitLink, an automatic redirect with a delay is wanted. Something like "You will now be taken to exitLink in 10 seconds …"
I’ve seen the setTimeout approach, the <META HTTP-EQUIV="refresh" CONTENT="seconds;URL=the-other-url"> approach, and even a form approach for achieving automatic redirects. Problem is, those seem intended for hard-coded, page-specific redirects. I haven’t been able to figure out how to adapt any of these to the js or the exit.html page to make them work. Sorry, I'm still low enough on the javascript learning curve that I can't seem to find the forest for the trees!
Any solution would be greatly appreciated! (Except php - I can't use that)
Here’s the javascript:
window.onload = function() {
wrapExitLinks();
}
function wrapExitLinks() {
var whiteList = "^gov^mil^";
var exitURL = document.location.protocol + "//" + document.location.host + "/exit.html"; // Default exit is /exit.html from referring site
var currentBaseURL = document.location.protocol + "//" + document.location.hostname + document.location.pathname;
var links = document.getElementsByTagName("a");
var linkDest;
var linkTLD;
var govTLD;
/* Do not wrap links on intersitial exit page */
if (currentBaseURL != exitURL) {
for (var i in links) {
if (links[i].host) {
linkTLD = links[i].hostname.substr(links[i].hostname.lastIndexOf(".") + 1); // Extract top level domain from target link
linkDest = links[i].href;
if (whiteList.indexOf("^" + linkTLD + "^") == -1) {
linkDest = exitURL + "?url=" + encodeURIComponent(linkDest);
links[i].href = linkDest;
}
}
}
} else {
confirmExit();
}
}
function confirmExit() {
var queryString = decodeURIComponent(document.location.search.substr(1));
var linkDest = queryString.substr(queryString.indexOf("url=") + 4);
var exitLink = document.getElementById("exitLink");
/* Assume http:// if no protocol provided */
if (linkDest.indexOf("://") == -1) {
linkDest = "http://" + linkDest;
}
exitLink.href = linkDest;
exitLink.innerHTML = linkDest;
}
The basic script you need is simply:
setTimeout(function () { window.location = 'http://example.com'; }, 10000);
That's all. Work it into your script somewhere.

&-sign is ruining my link-rewriter

I'm currently writing a userscript that runs on another site. One function is to rewrite the links so you skip one landing page. However, if the &-sign exists in the link, my function will output it as & instead of &.
$('a').each(function(index) {
var aLink = $(this).attr('href');
if(aLink) {
if(aLink.indexOf("leave.php?u=") > 0) {
aLink = aLink.substring(38);
$(this).attr('href', decodeURIComponent(aLink));
}
}
});
This is one example of a link that gets ruined:
https://www.site.com/exit.php?u=http%3A%2F%2Fsverigesradio.se%2Fsida%2Fartikel.aspx%3Fprogramid%3D104%26amp%3Bartikel%3D3406950
Is a link to:
http://sverigesradio.se/sida/artikel.aspx?programid=104&artikel=3406950
But becomes this instead:
http://sverigesradio.se/sida/artikel.aspx?programid=104&artikel=3406950
The & entity is built right into that URL, so there's nothing for it except to just replace it.
Use:
aLink = aLink.substring (38);
aLink = decodeURIComponent (aLink);
aLink = aLink.replace (/&/gi, "&");
$(this).attr ('href', aLink);

Categories

Resources