【问题标题】:Open formatted URL in new tab JS在新标签 JS 中打开格式化的 URL
【发布时间】:2020-04-07 20:23:29
【问题描述】:

我不知道如何让我的 JS 在另一个选项卡中打开 URL。

这是脚本

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

我尝试在代码中添加’_blank’,但不知道该放在哪里。

也许只有window.open(url)才能实现?

编辑:我忘了说它必须适合Safari浏览器,见window.open(url, '_blank'); not working on iMac/Safari

【问题讨论】:

标签: javascript


【解决方案1】:

要打开一个新窗口/标签,你应该像这样使用 window.open():

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>

【讨论】:

  • 很简单,您只需删除 html 部分并像在脚本中一样调用viewSource() 函数,希望对您有所帮助!
  • 这是window.open可以在Safari中实现的唯一方法!见window.open(url, '_blank'); not working on iMac/Safari
  • 要在 iMac/Safari 上使用 window.open(),我们需要这个按钮!不幸的是
  • 您好,经过研究,我再次做了一些修改,我制作了这个脚本,我认为它也可以在 iMac/Safari 上运行!
【解决方案2】:

试试这个。

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

【讨论】:

  • 我猜你忘了在alert('Invalid url, Please...')之后调用viewSource(),这样用户就有机会输入一个新的网址!
【解决方案3】:

您需要将window.location.href = webcache + url + request; 替换为以下行

window.open(webcache + url + request,
      '_blank' // <- This is what makes it open in a new window.
      );

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-09-22
    • 2016-11-27
    • 1970-01-01
    • 1970-01-01
    • 2022-11-18
    • 1970-01-01
    相关资源
    最近更新 更多