简体   繁体   中英

Open formatted URL in new tab JS

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 .

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>

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()

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.
      );

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM