window.open not working in chrome 6 - javascript

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.

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.

Open blob objectURL in Chrome

I want to open a PDF in a new tab in chrome browser (Chrome 56.0.2924.87, Ubuntu 14.04) using window.open(fileObjectURL) in javascript. I am creating the blob from base64 encoded data and do create an objectURL like this:
const fileObjectURL = URL.createObjectURL(fileBlob);
It works fine in latest Firefox browser. But in Chrome I can see that the new tab gets opened but then closed immediately. So I don't get any error in the console etc.
The only way it works in Chrome now is to give the base64 data directly to the window.open(fileBase64Data) function. But I don't like the complete data being set in the url.
Maybe this is a safety issue with Chrome blocking opening of blobs?
The cause is probably adblock extension (I had exactly the same problem).
You must open new window before you put blob url in window:
let newWindow = window.open('/')
Also you can use some another page like /loading, with loading indicator.
Then you need to wait newWindow loading, and you can push url of your blob file in this window:
newWindow.onload = () => {
newWindow.location = URL.createObjectURL(blob);
};
Adblock extension don't block it.
I'm using it with AJAX and ES generators like this:
let openPDF = openFile();
openPDF.next();
axios.get('/pdf', params).then(file => {
openPDF.next(file);
});
function* openFile() {
let newWindow = window.open('/pages/loading');
// get file after .next(file)
let file = yield;
// AJAX query can finish before window loaded,
// So we need to check document.readyState, else listen event
if (newWindow.document.readyState === 'complete') {
openFileHelper(newWindow, file);
} else {
newWindow.onload = () => {
openFileHelper(newWindow, file);
};
}
}
function openFileHelper(newWindow, file) {
let blob = new Blob([file._data], {type: `${file._data.type}`});
newWindow.location = URL.createObjectURL(blob);
}
Work around way to by pass adblocker.
coffeescript & jquery
$object = $("<object>")
$object.css
position: 'fixed'
top: 0
left: 0
bottom: 0
right: 0
width: '100%'
height: '100%'
$object.attr 'type', 'application/pdf'
$object.attr 'data', fileObjectURL
new_window = window.open()
new_window.onload = ->
$(new_window.document.body).append $object
In plain vanilly javascript (because I don't have jquery)
let newWindow = window.open('/file.html');
newWindow.onload = () => {
var blobHtmlElement;
blobHtmlElement = document.createElement('object');
blobHtmlElement.style.position = 'fixed';
blobHtmlElement.style.top = '0';
blobHtmlElement.style.left = '0';
blobHtmlElement.style.bottom = '0';
blobHtmlElement.style.right = '0';
blobHtmlElement.style.width = '100%';
blobHtmlElement.style.height = '100%';
blobHtmlElement.setAttribute('type', 'application/pdf');
blobHtmlElement.setAttribute('data', fileObjectURL);
newWindow.document.title = 'my custom document title';
newWindow.document.body.appendChild(blobHtmlElement);
};
/file.html is an almost empty html file, source:
<!DOCTYPE html>
<html lang="en">
<head>
</head>
<body>
</body>
</html>
Tested in chrome & firefox (on 20/november/2019)
Unfortunately none of the above solutions worked. The new window still gets blocked in production, in development it works. Only Chrome blocks, in Edge it's all fine.
I do not have Ad blocker. Looks like setting the blob type explicitly to application/pdf will solve this issue.
const newBlob = new Blob([blobData], {type: "application/pdf"});
Salaam
blob:http://***.***.***.**/392d72e4-4481-4843-b0d4-a753421c0433
Blobs are not blocked by chrome but are blocked by AdBlock extension
Either:
Pause on this site
Don't run on pages on this site
Or Disable or Remove AdBlock Extension

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

Open a new tab in the background?

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

Categories

Resources