Open a new tab in the background? - javascript

Using javascript, I want to open a new page in a different tab, but remain focused on the current tab. I know I can do it like this:
open('http://example.com/');
focus();
However, when I do this in chrome, it flashes the new tab for a moment before switching back to the current tab. I want to avoid this.
The application is a personal bookmarklet, so it only has to work in the latest Chrome.

UPDATE: By version 41 of Google Chrome, initMouseEvent seemed to have a changed behavior, and so this answer no longer works. Thanks to #Daniel Andersson for his comment.
this can be done by simulating ctrl + click (or any other key/event combinations that open a background tab) on a dynamically generated a element with its href attribute set to the desired url
In action: fiddle
function openNewBackgroundTab(){
var a = document.createElement("a");
a.href = "http://www.google.com/";
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);
}
tested only on chrome

This works well for me on all popular browsers:
function openNewBackgroundTab(){
var a = document.createElement("a");
a.href = window.location.pathname;
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);
}
var is_chrome = navigator.userAgent.toLowerCase().indexOf('chrome') > -1;
if(!is_chrome)
{
var url = window.location.pathname;
var win = window.open(url, '_blank');
} else {
openNewBackgroundTab();
}

As far as I remember, this is controlled by browser settings. In other words: user can chose whether they would like to open new tab in the background or foreground. Also they can chose whether new popup should open in new tab or just... popup.
For example in firefox preferences:
Notice the last option.

I did exactly what you're looking for in a very simple way. It is perfectly smooth in Google Chrome and Opera, and almost perfect in Firefox and Safari. Not tested in IE.
function newTab(url)
{
var tab=window.open("");
tab.document.write("<!DOCTYPE html><html>"+document.getElementsByTagName("html")[0].innerHTML+"</html>");
tab.document.close();
window.location.href=url;
}
Fiddle : http://jsfiddle.net/tFCnA/show/
Explanations:
Let's say there is windows A1 and B1 and websites A2 and B2.
Instead of opening B2 in B1 and then return to A1, I open B2 in A1 and re-open A2 in B1.
(Another thing that makes it work is that I don't make the user re-download A2, see line 4)
The only thing you may doesn't like is that the new tab opens before the main page.

Here is a complete example for navigating valid URL on a new tab with focused.
HTML:
<div class="panel">
<p>
Enter Url:
<input type="text" id="txturl" name="txturl" size="30" class="weburl" />
<input type="button" id="btnopen" value="Open Url in New Tab" onclick="openURL();"/>
</p>
</div>
CSS:
.panel{
font-size:14px;
}
.panel input{
border:1px solid #333;
}
JAVASCRIPT:
function isValidURL(url) {
var RegExp = /(ftp|http|https):\/\/(\w+:{0,1}\w*#)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%#!\-\/]))?/;
if (RegExp.test(url)) {
return true;
} else {
return false;
}
}
function openURL() {
var url = document.getElementById("txturl").value.trim();
if (isValidURL(url)) {
var myWindow = window.open(url, '_blank');
myWindow.focus();
document.getElementById("txturl").value = '';
} else {
alert("Please enter valid URL..!");
return false;
}
}
I have also created a bin with the solution on http://codebins.com/codes/home/4ldqpbw

Related

JS open url in new tab on background [duplicate]

Using javascript, I want to open a new page in a different tab, but remain focused on the current tab. I know I can do it like this:
open('http://example.com/');
focus();
However, when I do this in chrome, it flashes the new tab for a moment before switching back to the current tab. I want to avoid this.
The application is a personal bookmarklet, so it only has to work in the latest Chrome.
UPDATE: By version 41 of Google Chrome, initMouseEvent seemed to have a changed behavior, and so this answer no longer works. Thanks to #Daniel Andersson for his comment.
this can be done by simulating ctrl + click (or any other key/event combinations that open a background tab) on a dynamically generated a element with its href attribute set to the desired url
In action: fiddle
function openNewBackgroundTab(){
var a = document.createElement("a");
a.href = "http://www.google.com/";
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);
}
tested only on chrome
This works well for me on all popular browsers:
function openNewBackgroundTab(){
var a = document.createElement("a");
a.href = window.location.pathname;
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);
}
var is_chrome = navigator.userAgent.toLowerCase().indexOf('chrome') > -1;
if(!is_chrome)
{
var url = window.location.pathname;
var win = window.open(url, '_blank');
} else {
openNewBackgroundTab();
}
As far as I remember, this is controlled by browser settings. In other words: user can chose whether they would like to open new tab in the background or foreground. Also they can chose whether new popup should open in new tab or just... popup.
For example in firefox preferences:
Notice the last option.
I did exactly what you're looking for in a very simple way. It is perfectly smooth in Google Chrome and Opera, and almost perfect in Firefox and Safari. Not tested in IE.
function newTab(url)
{
var tab=window.open("");
tab.document.write("<!DOCTYPE html><html>"+document.getElementsByTagName("html")[0].innerHTML+"</html>");
tab.document.close();
window.location.href=url;
}
Fiddle : http://jsfiddle.net/tFCnA/show/
Explanations:
Let's say there is windows A1 and B1 and websites A2 and B2.
Instead of opening B2 in B1 and then return to A1, I open B2 in A1 and re-open A2 in B1.
(Another thing that makes it work is that I don't make the user re-download A2, see line 4)
The only thing you may doesn't like is that the new tab opens before the main page.
Here is a complete example for navigating valid URL on a new tab with focused.
HTML:
<div class="panel">
<p>
Enter Url:
<input type="text" id="txturl" name="txturl" size="30" class="weburl" />
<input type="button" id="btnopen" value="Open Url in New Tab" onclick="openURL();"/>
</p>
</div>
CSS:
.panel{
font-size:14px;
}
.panel input{
border:1px solid #333;
}
JAVASCRIPT:
function isValidURL(url) {
var RegExp = /(ftp|http|https):\/\/(\w+:{0,1}\w*#)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%#!\-\/]))?/;
if (RegExp.test(url)) {
return true;
} else {
return false;
}
}
function openURL() {
var url = document.getElementById("txturl").value.trim();
if (isValidURL(url)) {
var myWindow = window.open(url, '_blank');
myWindow.focus();
document.getElementById("txturl").value = '';
} else {
alert("Please enter valid URL..!");
return false;
}
}
I have also created a bin with the solution on http://codebins.com/codes/home/4ldqpbw

showing popup window behind main window using javascript

i want to make my pop up window will showing behind main windows.
say it window 1 is main windows and window 2 is popup window.
so when someone click window 1, window 2 will pop up behind window 1.
im already try window.focus and window.blur but no one working. remember this, I'm just making this one for learning.
<script type="text/javascript">
var popup = function() {
var lastShownTs = +localStorage.getItem("lastShown");
var currentDate = new Date();
currentDate.setHours(0, 0, 0, 0);
var lastShown = null;
if (!isNaN(lastShownTs)) {
lastShown = new Date(lastShownTs);
lastShown.setHours(0, 0, 0, 0);
}
if (lastShown == null || lastShown.getTime() != currentDate.getTime()) {
window.open("example.com", "Window", "status=1,toolbar=1,width=1,height=1,left=5000,top=5000,scrollbars=1,resizable=1");
localStorage.setItem("lastShown", currentDate.getTime());
}
window.focus();
popup.blur();
}
</script>
<body onclick="popup()"></body>
I believe what you are looking for is referred to as a "Pop-under".
See https://developer.mozilla.org/en-US/docs/Web/API/Window/open.
Alternately, here is a cheat using tabs ...
<script>
function popunder() {
var currentURL = document.URL;
window.open(currentURL, '_blank', 'toolbar=yes, location=yes, status=yes, menubar=yes, scrollbars=yes');
window.location = 'http://www.stackoverflow.com';
}
</script>
Click here!
Tested Chrome 62.0.3202.62.

How to save data in local hd with javascript?

I'm using CKEditor to create text in a website that create documents. The problem is the internet connection, the PC is far away from town and it's unstable 3G connection. I already have a routine to save a draft every ten seconds (or the time the user wish to be) in the server for safe - simple task. The problem is that if the internet goes down, the user will have to select - copy the text and try to save it locally with some text editor (maybe Word, that will make a mess).
So I'm wondering if already exists a way of to create a file and download to the local HD without remote server, just the JavaScript and navigator. Also, it might be another way to save the job but keeping CPU on and navigator open, but couldn't find in stack overflow.
I found just one non-standard API FireFox compatible:
Device Storage API
Of course, is not JavaScript standard so I don't know if it's a good idea to use right now.
Any ideas?
[Compatibility Note]
This solution uses <a> attribute download, to save the data in a text file.
This html5 attribute is only supported by Chrome 14+, Firefox 20+ and Opera
15+ on
desktop, none on iOS and all current majors except WebView on Android.
-A workaround for IE 10+ is to not hide/destroy the link generated by clickSave()and ask user to right-click > Save target As…
-No known workaround for Safari.
Also note that data will still be accessible via
localStorage.getItem()
for Firefox 3.5+, Chrome&Safari 4+, Opera 10.5+ and IE 9+ (xhr will
crash IE 8-)
I would do it like so, assuming your actual code saves the data via xhr.
function saveData() {
var xhr = new XMLHttpRequest();
//set a timeout, in ms, to see if we're still connected
xhr.timeout = 2000;
xhr.addEventListener('timeout', localStore, false);
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
// not a good news
if (xhr.status !== 200) {
localStore();
}
else{
document.querySelector('#local_alert').style.display = 'none';
}
}
}
//I assume you already have the part where you set the credentials
xhr.open('POST', 'your/url.php');
xhr.send();
}
//Show the link + Store the text in localStorage
function localStore() {
document.querySelector('#local_alert').style.display = 'block';
var userText = document.querySelector('textArea').value;
localStorage.setItem("myAwesomeTextEditor", userText);
}
//provide a link to download a file with txt content
window.URL = window.URL || window.webkitURL;
function clickSave(e) {
var userText = document.querySelector('textArea').value;
var blob = new Blob([userText], {type: 'plain/text'});
var a = document.createElement('a');
a.download = "myAwesomeTextEditor" + (new Date).getTime() + '.txt';
a.href = URL.createObjectURL(blob);
a.style.display = "none";
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
}
setInterval(saveData, 3000);
#local_alert {
display: none;
position: static;
width: 100%;
height: 3em;
background-color: #AAA;
color: #FFF;
padding: 0.5em;
}
body,
html {
margin: 0
}
<div id="local_alert">You're actually offline, please beware your draft is not saved on our server
<button onclick="clickSave()">Save Now</button>
</div>
<textarea></textarea>
Ps: If your user leaves the page without connection, you'll be able to get the text back via localStorage.getItem("myAwesomeTextEditor")
PPs: A more "live" example can be found here (it won't save to server but you've got the rest of the logic working). Try to disconnect , then reconnect.
Try
var editor = document.getElementById("editor");
var saveNow = document.getElementById("save");
function saveFile() {
if (confirm("save editor text")) {
var file = document.createElement("a");
file.download = "saved-file-" + new Date().getTime();
var reader = new FileReader();
reader.onload = function(e) {
file.href = e.target.result;
document.body.appendChild(file);
file.click();
document.body.removeChild(file);
};
reader.readAsDataURL(new Blob([editor.value], {
"type": "text/plain"
}));
}
};
saveNow.addEventListener("click", saveFile, false);
<button id="save">save editor text</button><br />
<textarea id="editor"></textarea>

JavaScript open new window, but focus shoud remain on old window

Objective :
I want to open a new window but the focus remain on old window.
what I tried :
<button id="test">Open Google</button>
-
document.getElementById("test").addEventListener("click", openNewBackgroundTab, false);
function openNewBackgroundTab(){
var a = document.createElement("a");
a.href = "http://www.google.com/";
var evt = document.createEvent("MouseEvents");
evt.initMouseEvent("click", true, true,
window, 0, 0, 0, 0, 0,
true, false, false, false,
0, null);
a.dispatchEvent(evt);
}
Here is the link : JSFiddle
This works fine in Chrome but not in Mozilla.
Please help !!
This behaviour is up to the browser and can't be controlled by JavaScript.
write onload event of the new window
window.opener.focus();

window.open not working in chrome 6

I am trying to open a location in new window(tab) using window.open. It is not working in chrome. First I tried with window.open(url,name), this did not work, however this works in every other browser. Then I used something like this,
var w = window.open("about:blank");
w.opener = null;
w.document.location = url;
This opens the url in same tab but not in separate tab.
Are you sure your popup is not being blocked? Most popup windows that didn't happen in response to a user event will get blocked. I typed window.open("google.com", "_blank") into the console and I got the blocked window on the url bar
Do it like this
window.open( url, "_blank" );
Remember, the 2nd parameter is analogous to an anchor tag's target attribute.
Try this. Works in IE8, fails in FF when popups are blocked
<html>
<head>
<script type="text/javascript">
if(typeof HTMLElement!='undefined'&&!HTMLElement.prototype.click)
HTMLElement.prototype.click=function(){ // event by Jason Karl Davis
var evt = this.ownerDocument.createEvent('MouseEvents');
evt.initMouseEvent('click', true, true, this.ownerDocument.defaultView, 1, 0, 0, 0, 0, false, false, false, false, 0, null);
this.dispatchEvent(evt);
}
function loadAndClick(url,target) {
var lnk = document.createElement("a");
lnk.href=url;
lnk.target=target||"_blank"
lnk.id="myLink"
lnk.onclick=function() {
var w = window.open(this.href,this.target);
return (w)?false:true;
}
document.body.appendChild(lnk);
document.getElementById('myLink').click();
// lnk.click();
}
window.onload=function() { // or call getURL("javascript:loadAndClick('http://www.google.com')");
loadAndClick("http://www.google.com");
}
</script>
</head>
<body>
</body>
</html>
Create a redirect page (for example Redirect.aspx).
window.open('Redirect.aspx?URL=http://www.google.com', '_blank');
From the Redirect.aspx page, redirect to the URL specified in the QS...
This worked a treat for me with Chrome blocking my new windows.

Categories

Resources