使用Javascript在新窗口中打开URL

Mar*_*ell 115 javascript

我正在制作一个"分享按钮"来分享当前页面.我想获取当前页面URL并在新窗口中打开它.我有当前的URL部分工作,但似乎无法使下一部分工作.

我正在努力学习语法.我想指定新的窗口大小width=520, height=570.

就像是:

<a target="_blank" href="https://www.linkedin.com/cws/share?mini=true&amp;url=[sub]" onclick="this.href = this.href.replace('[sub]',window.location)">LinkedIn</a>
Run Code Online (Sandbox Code Playgroud)

有任何想法吗?

cit*_*spi 194

用途window.open():

<a onclick="window.open(document.URL, '_blank', 'location=yes,height=570,width=520,scrollbars=yes,status=yes');">
  Share Page
</a>
Run Code Online (Sandbox Code Playgroud)

这将创建一个标题Share Page链接,在新窗口中打开当前URL,高度为570,宽度为520.

  • 我们如何将其作为普通窗口而不是弹出窗口打开?因为无法打开新标签 (2认同)

Shi*_*dim 52

只是使用window.open()功能?第三个参数允许您指定窗口大小.

var strWindowFeatures = "location=yes,height=570,width=520,scrollbars=yes,status=yes";
var URL = "https://www.linkedin.com/cws/share?mini=true&amp;url=" + location.href;
var win = window.open(URL, "_blank", strWindowFeatures);
Run Code Online (Sandbox Code Playgroud)

  • @MarkMitchell如果您不关心编码标准,请添加到`onclick`属性中。更好的选择是创建一个从onclick调用的函数。使用`getElementById`和`addEventListener`更加干净。使用jQuery获得较短的语法(以及一些其他功能+大量的插件)也很受欢迎。 (2认同)

Rix*_*unt 8

我知道已经太晚了,但是,

在新选项卡中打开链接的步骤:

  1. 创建一个a元素
  2. 设置href ( "https://example.com")
  3. 设置target"_blank"
  4. 点击链接

代码

<button onclick="myFunction()">Open</button>
<script>
function myFunction() {
  var link = document.createElement("a")
  link.href = "https://example.com"
  link.target = "_blank"
  link.click()
}
</script>
Run Code Online (Sandbox Code Playgroud)


小智 7

不要混淆,如果您不提供任何 strWindowFeatures,那么它将在新选项卡中打开。

window.open('https://play.google.com/store/apps/details?id=com.drishya');
Run Code Online (Sandbox Code Playgroud)