如何在不切换到新标签的情况下使用 javascript 打开新标签?
例如,当用户单击链接时,将打开一个新选项卡,但用户应停留在当前选项卡上。
如何在不切换到新标签的情况下在 JavaScript 中打开新标签?
IT技术
javascript
html
2021-03-15 15:46:34
6个回答
Web 浏览器会自动将焦点放在新选项卡上,但您可以回调焦点:
function openWindow( url )
{
window.open(url, '_blank');
window.focus();
}
<a href="http://www.example.com/" onclick="javascript:openWindow(this.href);return false;">Click Me</a>
不幸的是,你目前不能这样做——但你可以接近。您可以打开一个新窗口,如果您在不指定任何窗口尺寸或窗口功能的情况下执行此操作,大多数现代浏览器将改为打开一个新选项卡(取决于用户的偏好,但是,无论如何,您都希望执行用户喜欢的操作,对?)。所以只是window.open(url)
或者window.open(url, name)
如果你打算使用这个名称来做某事。务必在直接响应用户启动的事件时执行此操作,否则浏览器的弹出窗口阻止程序可能会...阻止弹出窗口。:-)
关于将注意力集中在你的窗户上……祝你好运。您可以window.focus()
在 之后调用window.open(...)
,但根据我的经验,它通常不起作用。
把它扔出去:如果你让用户与带有 URL 的真实链接交互,用户可以决定是否在新选项卡、新窗口等中打开它,以及是否给它焦点(如果他们是足够复杂,可以知道 Shift+Click 和 Ctrl+Shift+Click,或右键单击菜单)。
不幸的是,您无法在所有浏览器中执行此操作,但如果您实现了浏览器的扩展程序,则可以在 Chrome 中执行此操作。如何通过 javascript 操作 Chrome 中的标签:
http://code.google.com/chrome/extensions/tabs.html
chrome.tabs.create(object createProperties, function callback)
Creates a new tab. Note: This function can be used without requesting the 'tabs' permission in the manifest.
Parameters
**createProperties** ( object )
**windowId** ( optional integer )
The window to create the new tab in. Defaults to the current window.
**index** ( optional integer )
The position the tab should take in the window. The provided value will be clamped to between zero and the number of tabs in the window.
**url** ( optional string )
The URL to navigate the tab to initially. Fully-qualified URLs must include a scheme (i.e. 'http://www.google.com', not 'www.google.com'). Relative URLs will be relative to the current page within the extension. Defaults to the New Tab Page.
**selected** ( optional boolean )
Whether the tab should become the selected tab in the window. Defaults to true
pinned ( optional boolean )
Whether the tab should be pinned. Defaults to false
**callback** ( optional function )
这是用户特定的设置,您无法从 JS 更改此行为。
(function(a) {
document.body.appendChild(a);
a.setAttribute('href', location.href);
a.dispatchEvent((function(e) {
e.initMouseEvent("click", true, true, window, 0, 0, 0, 0, 0,
true, false, false, false, 0, null);
return e
}(document.createEvent('MouseEvents'))))
}(document.createElement('a')))
其它你可能感兴趣的问题