Reputation: 57
I cannot figure how to get my JS to open the URL in another tab.
Here’s the script
function viewSource(){
var webcache = "http://webcache.googleusercontent.com/search?q=cache:";
var request = "&prmd=ivn&strip=0&vwsrc=1";
var url = window.prompt("Enter valid URL");
window.location.href = webcache + url + request;
}
viewSource();
I tried adding ’_blank’
in the code, but I couldn’t figure where to place it.
Maybe it can only be achieved with window.open(url)
?
Edit: I forgot to mention that it must be suitable for Safari browsers, see window.open(url, '_blank'); not working on iMac/Safari.
Upvotes: 1
Views: 871
Reputation: 683
To open a new window/tab you should use window.open() just like that:
function viewSource(){
var webcache = "http://webcache.googleusercontent.com/search?q=cache:";
var request = "&prmd=ivn&strip=0&vwsrc=1";
var url = window.prompt("Enter valid URL");
const Link=webcache+url+request;
//Check for myService object (Refers to iMac/Safari)
if(typeof myService!="undefined"&&typeof myService.getUrl!="undefined"){
const windowReference = window.open();
myService.getUrl().then(function(url) {
windowReference.location = Link;
});
//Otherwise, we can just open a normal window ( Chrome, Firefox, ..)
}else window.open(Link, '_blank');
return Link;
}
<button onclick="viewSource();">Open Link</button>
Upvotes: 3
Reputation: 10569
Try this.
function viewSource() {
var webcache = "http://webcache.googleusercontent.com/search?q=cache:";
var request = "&prmd=ivn&strip=0&vwsrc=1";
var url = window.prompt("Enter valid URL");
if (url && url.match(/^((([A-Za-z]{3,9}:(?:\/\/)?)(?:[\-;:&=\+\$,\w]+@)?[A-Za-z0-9\.\-]+|(?:www\.|[\-;:&=\+\$,\w]+@)[A-Za-z0-9\.\-]+)((?:\/[\+~%\/\.\w\-_]*)?\??(?:[\-\+=&;%@\.\w_]*)#?(?:[\.\!\/\\\w]*))?)/g)) {
window.open(
webcache + url + request,
'_blank'
);
} else {
alert('Invalid url, Please enter a valid url');
viewSource();
}
}
viewSource()
Upvotes: 1
Reputation: 1004
you need to replace window.location.href = webcache + url + request;
with following line
window.open(webcache + url + request,
'_blank' // <- This is what makes it open in a new window.
);
Upvotes: 0