简体   繁体   中英

How to use javascript to write to a new tab that was opened in the background

I am trying to do two things, 1. I need to open a new tab in the background without giving it focus, and 2. I need to be able to write to that page using javascript. (I only care about it working on Chrome)

Now if I use this code....

var handle = window.open("text/html", '_blank');
handle.document.write(reportPath);
handle.document.title = "Export Report";

I can open a new and write to it, HOWEVER, that window gets shoved in your face, which I do not want to happen, because it interrupts my user's workflow badly (I want to keep focus on the previous window).

However, I can use this code....

var a = document.createElement("a");
a.href = "about:blank";
a.target='_blank'
var evt = document.createEvent("MouseEvents");
//the tenth parameter of initMouseEvent sets ctrl key
evt.initMouseEvent("click", true, true, window, 0, 0, 0, 0, 0, true, false, false, false, 0, null);
a.dispatchEvent(evt);

Which works beautifully (it opens the new tab in the background), HOWEVER, I am unable to write to the new window that was opened because I cannot get the new window's handle.

Can somebody please tell me how I can either use the first method to open that window without giving it focus, or tell me how to use the second window, but somehow get the handle of that window so that I can write to it.

As I said before I only need this code to work for Chrome, it's a web app for my company and everybody here uses Chrome, so I don't care if it works with other browsers.

除了上述答案外,您还可以为新窗口执行handle.blur()来失去焦点。

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