I'm trying to open multiple links at once in Google Chrome in new tabs but it fails.
Problems:
Blocked by popup
Open in new windows instead of tab after the user allowed the popup
With this, I can open multiple links at once in Firefox:
<!DOCTYPE html>
<html ng-app="plunker">
<head>
<meta charset="utf-8">
<title>AngularJS Plunker</title>
<script>document.write('<base href="' + document.location + '" >');</script>
<link rel="stylesheet" href="style.css">
<script data-require="angular.js#1.2.x" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.17/angular.min.js" data-semver="1.2.17"></script>
<script src="app.js"></script>
</head>
<body ng-controller="MainCtrl">
<button ng-click="openLinks()">Open</button>
</body>
</html>
Also, I came across someone who found a workaround.
I tried using setInterval to try to open the links individually but it didn't work.
You can do this in vanilla JavaScript:
<html>
<head>
<script type="text/javascript">
function open_win() {
window.open("http://www.java2s.com/")
window.open("http://www.java2s.com/")
}
</script>
</head>
<body>
<form>
<input type=button value="Open Windows" onclick="open_win()">
</form>
</body>
</html>
Here is a more Chrome-specific implementation (if popup blockers are giving you difficulty):
var linkArray = []; // your links
for (var i = 0; i < linkArray.length; i++) {
// will open each link in the current window
chrome.tabs.create({
url: linkArray[i]
});
}
Here is some documentation: https://developer.chrome.com/extensions/tabs
The reason that the browser extension can do it is because Chrome extensions have access to a special Chrome API, which lets you use:
chrome.windows.create({tabid: n})
where createData has a tabid value greater than any current tab (and you can find the greatest current tabid using chrome.windows.getAll()).
However, in terms of doing it on your page (or anywhere that's not a Chrome extension), that's not possible, since whether or not a new window opens in a new tab is determined entirely by the user's settings.
The best way to open multiple tabs or windows is by using setTimeout() of 500ms.
window.open("https://facebook.com", "one", windowFeatures);
setTimeout(function(){
window.open("https://facebook.com", "two", windowFeatures);
}, 500);
User will have to allow popups but I ended up doing this:
function openMultipleTabs(urlsArray){
urlsArray.forEach(function(url){
let link = document.createElement('a');
link.href = url;
link.target = '_blank';
link.click();
});
}
Worth mentioning that you need to actually have popups allowed in your browser settings. Don't rely on browser alert asking you if you want to allow the popup to open.
The following code will open multiple popUp on the button click.
<html>
<head>
<title></title>
<script type="text/javascript">
function open_win() {
window.open("url","windowName","windowFeatures")
window.open("url","DifferentWindowName","windowFeatures")// different name for each popup
}
</script>
</head>
<body>
<form>
<input type=button value="Open Windows" onclick="open_win()">
</form>
</body>
you need to make sure that each window name is different, otherwise the last popup will overwrite it's previous popup. As a result you will end up with a single popup.
I have a simple solution playing with setTimeout, check below
function openMultipleTabs(urlsArray: string[]) {
urlsArray.forEach((url: string, key: number) => {
if (key === 0) {
window.open(url, `_blank_first_${key.toString()}`);
} else {
setTimeout(function () {
console.log("resolved", key);
window.open(url, `_blank_${key.toString()}`);
}, 1500 * key);
}
});
}
Looks like extension uses below code to open those tabs.
function openTab(urls, delay, window_id, tab_position, close_time) {
var obj = {
windowId: window_id,
url: urls.shift().url,
selected: false
}
if(tab_position != null) {
obj.index = tab_position
tab_position++;
}
chrome.tabs.create(obj, function(tab) {
if(close_time > 0) {
window.setTimeout(function() {
chrome.tabs.remove(tab.id);
}, close_time*1000);
}
});
if(urls.length > 0) {
window.setTimeout(function() {openTab(urls, delay, window_id, tab_position, close_time)}, delay*1000);
}
}
If you want to take a look at the code of the extension for reference you will find the extensions in (for Windows) C:\Documents and Settings\*UserName*\Local Settings\Application Data\Google\Chrome\User Data\Default\Extensions
Since modern browsers (and even old ones with blockers), will absolutely not allow this (one user action, one new tab). My solution was:
openInfoLinks = () => {
const urlsArray = [
`https://...`,
`https://...`,
`https://...`,
]
window.open(
urlsArray[this.linkCounter],
`_blank_${someIdentifier}_${this.linkCounter}`
);
this.linkCounter++;
setTimeout(() => {
this.linkCounter = 0;
}, 500);
}
The user can open the links in quick succession with ctrl+click-ing the button N times.
Related
I have the following scenario like this :
I have a main window[main.html]. There are three links called Popup1, Popup2, Popup3. On clicking the link open Popup1 window, Popup2 window respectively.
<html>
<head>
<title>Popup Focus Example</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8/jquery.min.js"></script>
<script>
var openWin = [];
$(function(){
$('#elem').on('click', 'a', function(){
var index = $(this).index();
var page = 'pop'+(index+1)+'.html';
var w = window.open(page, $(this).attr('title'), '_blank');
openWin[index] = w;
});
});
</script>
</head>
<body>
<div id="elem">
Pop 1
Pop 2
Pop 3
</div>
</body>
</html>
Now the windows open are window 1 & window 2. I want to transfer the focus of the window 1 from window 2. is there anyway this can be done?
pop1.html
<html>
<head>
<title>Popup 1 Example</title>
<script type="text/javascript">
function go() {
if(window.opener.openWin) {
var popup2 = window.opener.openWin[1];
popup2.focus();
}
}
</script>
</head>
<body>
<div>
popup 1 example
</div>
<div>Go to Popup2</div>
</body>
</html>
pop2.html
<html>
<head>
<title>Popup 2 Example</title>
</head>
<body>
<div>
popup 2 example
</div>
</body>
</html>
Check main.html code in fiddle http://jsfiddle.net/tmf8cry8/2/
You have written the code properly, please implement the two changes as listed below...
1) You need to push the window object in openWin Array
var openWin = [];
$(function(){
$('#elem').on('click', 'a', function(){
var index = $(this).index();
var page = 'pop'+(index+1)+'.html';
var w = window.open(page, $(this).attr('title'), '_blank');
//openWin[index] = w;
openWin.push(w); //Push the window object
});
});
2) Access the window object using the array index to focus the window
function go() {
//console.log(openWin);
//if(window.opener.openWin) {
// var popup2 = window.opener.openWin[1];
//popup2.focus();
//}
//Supposing that pop1, pop2 and pop3 are opened, you want to access pop2
openWin[1].focus();
}
Hope it helps!
You can use the method window.open
window.open("",window_name).focus();
Assuming your window is opened, you can transfer focus to the window using the above code.
Please use the following code in pop2.html and try [after opening all windows in a sequential order].
<html>
<head>
<title>Popup 2 Example</title>
<script language="javascript">
function openNew()
{
window.open("","Pop 3").focus();
}
</script>
</head>
<body>
<div>
popup 2 example
</div>
<a href="javascript:void(0);" onclick="javascript:openNew();">
Go to pop3</a>
</body>
</html>
As per you code, you are using title attribute to naming windows, hence Pop 3 is used to transfer focus to Pop 3 window.
Alternatively, you may check if the window instance is opened or not and then load the URL entirely or transfer focus
Hope it helps!!!
Make go() function just call a function in the opener window, e.g.:
window.blur(); //focus out of here
window.opener.myParentWindowFunction( 2 );
That function (in the "parent" window) should call then a function in the target window that just "window.focus()".
funtion myParentWindowFunction( target ){
window.blur();//focus out of here also
openWin[target].callFocus();
}
And on every popup:
function callFocus(){ window.focus(); }
You can't make a window "send" the focus to another (security issues I guess), but you can make a window to "ask for it"... and depends on the browsers if it's going to get it (in chrome doesn't work, but if you add an alert() after the focus it will change the window. Funny, because if you just put the alert but not the focus it doesn't swap the windows...)
Code is just a mockup, but that's the concept. You have to use the opener window as relay comunicate to the desired window that it have to call the focus. Hope you don't need it really crossbrowser.
I'm struggling trying to get a link to pop up in in the Dropbox chooser drop-in app. I'm using the javascript method and inserting into an html page. The dropbox chooser button shows up, and I'm able to select a file from the dropbox pop-up window, but the result is just a green checkmark and NO link like in the demo (I've tried both the direct and preview method). I've been struggling with this for a few hours. Anyone see anything wrong, or have a good code snipeet they want to share?
Here's my code:
<script type="text/javascript" src="https://www.dropbox.com/static/api/1/dropins.js" id="dropboxjs" data-app-key="XXXXXX"></script>
<!-- Replace data-app-key with yours --> <script type="text/javascript">
// add an event listener to a Chooser button
document.getElementById("db-chooser").addEventListener("DbxChooserSuccess",
function(e) {
alert("Here's the chosen file: " + e.files[0].link)
window.location.href = 'e.files[0].link';
}, false);
</script>
<input data-link-type="direct" id="db-chooser" name="selected-file" type="dropbox-chooser" />
<div id="link-div" style="display: none">Link:</div>
<script type="text/javascript">
document.getElementById("db-chooser").addEventListener("DbxChooserSuccess",
function(e) {
var link = document.getElementById("link");
link.textContent = link.href = e.files[0].link;
document.getElementById("link-div").style.display = "block";
}, false);
</script>
I see two issues in the above code.
The first script references db-chooser before it's actually on the page, so that may not be working at all.
The second script looks for an element called link, but I think you mean link-div.
Finally, you might want to update to the latest version of dropins.js, just because it's the latest. :-) The input tag version has gone away, and instead you can use createChooseButton. Here's a complete working example using the latest version:
<!doctype html>
<html>
<head>
<script src="https://www.dropbox.com/static/api/2/dropins.js" id="dropboxjs" data-app-key="XXXXXX"></script>
</head>
<body>
<div id="container"></div>
<a id="link"></a>
<script>
var button = Dropbox.createChooseButton({
success: function(files) {
var linkTag = document.getElementById('link');
linkTag.href = files[0].link;
linkTag.textContent = files[0].link;
},
linkType: 'direct'
});
document.getElementById('container').appendChild(button);
</script>
</body>
</html>
I made a few changes to the MEjs demo player, to enable playback of OGG in IE/Safari browsers, using the Cortado Java applet.
I have play/pause working, and although getPlayPosition() isn't getting the current position in milliseconds as described in the documentation, applet.currentTime and applet.duration work well for this purpose.
I thought it would be simple to hook these up to the current position indicators on the mejs player, but I'm running into a problem. setCurrentTime on the object is causing DOM Exception: InVALID_STATE_ERR (11) in IE, and a similar error happens in Safari. Apparently the object I'm trying to set no longer exists?
The code below will play and pause, and even give the seconds/total in the console (F12 tools MUST be enabled in IE.) Is there a good way to connect this to the play bar?
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>HTML5 MediaElement</title>
<script src="../build/jquery.js"></script>
<script src="../build/mediaelement-and-player.js"></script>
<link rel="stylesheet" href="../build/mediaelementplayer.min.css" />
</head>
<body>
<h1>MediaElementPlayer.js</h1>
<p>Audio player</p>
<h2>OGG Player</h2>
<audio id="player2" src="http://www.archive.org/download/memoirs_holmes_0709_librivox/holmesmemoirs02doyle.ogg" type="" controls="controls">
</audio>
<script>
MediaElementPlayer.prototype.buildplaypauseOrig =
MediaElementPlayer.prototype.buildplaypause;
MediaElementPlayer.prototype.buildplaypause = function(a,b,c,d) {
if (d.src.indexOf('.ogg') !=-1 /* && IE or safari */) {
if (jQuery(this.$node).find('applet').length==0) {
jQuery(this.$node).append('<applet code="com.fluendo.player.Cortado.class" codebase="http://theora.org/" archive="cortado.jar" width="100" height="100">'+
'<param name="url" value="'+d.src+'"/><param name="seekable" value="true"/><param name="autoPlay", value="false"/></applet>');
}
var el = this.$node; //mejs audio element
var initonload = function() {
if (el.find('applet')[0].isActive) {
var applet = el.find('applet')[0];
// This is where it fails: mejs.players[0].setCurrentTime or d.setCurrentTime cause dom exception
console.log(applet.code);
console.log(applet.currentTime);
/*mejs.players[0]*/ //d.setCurrentTime(applet.currentTime);
console.log(applet.duration);
/*mejs.players[0]*/ //d.media.duration = applet.duration;
} else {
window.setTimeout(initonload,100);
}
}
d.addEventListener("play",function() {
var audio = el.attr('src');
window.setInterval(function() {
//try {
var applet = el.find('applet')[0];
console.log(applet.currentTime);
// This is where it fails: mejs.players[0].setCurrentTime or d.setCurrentTime cause dom exception
//mejs.players[0].setCurrentTime(applet.currentTime);
console.log(applet.duration);
/*mejs.players[0]*/ //d.media.duration = applet.duration;
//}catch(e) {console.log(e)}
//console.log(applet.getPlayPosition()+"ms");
},1000);
//jQuery(this).find('applet')[0].setParam('url',audio);
el.find('applet')[0].doPlay();
});
d.addEventListener("pause",function() {
var applet = el.find('applet')[0];
applet.doPause();
});
d.addEventListener("load",function(e) {
alert('load');
});
}
this.buildplaypauseOrig(a,b,c,d);
}
mejs.HtmlMediaElementShim.determinePlaybackOrig =
mejs.HtmlMediaElementShim.determinePlayback
mejs.HtmlMediaElementShim.determinePlayback = function(htmlMediaElement, options, supportsMediaTag, isMediaTag, src) {
var res = this.determinePlaybackOrig(htmlMediaElement, options, supportsMediaTag, isMediaTag, src);
//if (mejs.MediaFeatures.isIE) {
res.method = 'native';
//}
return res;
}
$('audio,video').mediaelementplayer();
</script>
</body>
</html>
This is using MeJS 2.10.3.
[EDIT]
After inspecting the MediaElement.js code, it seems that mejs.players is not an array, but an object, and in order to access the first player, you would have to look into mejs.players['mep_0'], since mejs.players[0] would be undefined.
My guess would be that jQuery fails to create an interactive <applet> element, since, from my experience, jQuery (which heavily relies on document.createDocumentFragment) sometimes fails to attach/trigger events on dynamically created/cloned DOM nodes, especially in IE, which could be the cause for this DOM error that you're seeing, because your <applet> object probably failed to initialize.
To try and fix this problem, I'd suggest to use the native document.createElement and document.appendChild methods instead of the jQuery.append.
if (jQuery(this.$node).find('applet').length==0) {
var createElem = function(name, attributes) {
var el = document.createElement(name);
attributes = attributes || {};
for (var a in attributes) {
el.setAttribute(a, attributes[a]);
}
return el;
};
var applet = createElem('applet',{
code:'com.fluendo.player.Cortado.class',
codebase: 'http://theora.org/',
archive: 'cortado.jar',
width: 100,
height: 100
});
applet.appendChild(createElem('param', {name:'url', value:d.src}));
applet.appendChild(createElem('param', {name:'seekable', value: 'true'}));
applet.appendChild(createElem('param', {name:'autoPlay', value: 'false'}));
this.$node.get(0).appendChild(applet);
}
I'm really new to JavaScript, but I think this should be pretty simple. I'm just trying to create a link to close my window using: document.write("Close this window");
However, when I click the link created by the above code nothing happens. What am I doing wrong? my entire code is below:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Loops demo</title>
</head>
<body>
<script type="text/javascript">
function openActor() {
actorWin = window.open("","actorWin","height=200,width=600,resizable");
actorWin.document.write("<!doctype html>");
actorWin.document.write("<html lang=\"en\">");
actorWin.document.write("<head>");
actorWin.document.write("<meta charset=\"utf-8\">");
actorWin.document.write("<title>Keira Knightley</title>");;
actorWin.document.write("</head>");
actorWin.document.write("<body>");
actorWin.document.write("Info on, one of the great actors of our time.");
actorWin.document.write("</body>");
actorWin.document.write("</html>");
}
function Movie(title, actor, web1, web2) {
this.title = title;
this.actor = actor;
this.link = web1;
this.link2 = web2;
}
var movie1 = new Movie('Pride and Prejudice', 'Keira Knightley', 'http://movies.yahoo.com/movie/pride-and- prejudice-2005/','http://keiraknightleyfan.com/');
document.write(movie1.title + '<blockquote>“A lady\'s imagination is very rapid; it jumps from admiration to love, from love to matrimony in a moment.” ― Jane Austen, Pride and Prejudice</blockquote>');
document.write('Read more about Pride Prejudice<br>');
document.write("<a href='javascript:openActor()'>Click here for info on the lead actor</a><br>");
document.write("<a href='javascript:close()'>Close this window</a>");
</script>
</body>
</html>
You cannot close windows by using close() when they haven't been opened via javascript
There is no function named close.
javascript:close(); simply calls the function close.
If you want to close the popup window, you will need to call close on that.
Like: javascript:actorWin.close();
In that case, make sure you declare the actorWin in the global scope (put var actorWin; just above function openActor...).
Try window.close()
document.write("<a href='javascript:window.close()'>Close this window</a>");
In my background (background.html) page I have the following js:
function capturePage(){
chrome.tabs.captureVisibleTab(null, function(img){
var screenshotUrl = img;
chrome.tabs.create({"url":"history.html"}, function(tab){
var t = tab;
var addImage = function(){
var view = chrome.extension.getViews()[0];
view.setImageUrl(screenshotUrl);
}
chrome.tabs.onUpdated.addListener(addImage);
});
});
}
chrome.browserAction.onClicked.addListener(capturePage);
and in history.html I have:
<html>
<head>
<title></title>
<script>
function setImageUrl(url){
document.getElementById("target").src = url;
}
</script>
</head>
<body>
<img id="target" src="" >
</body>
</html>
However, "view.setImageUrl(screenshotUrl)", in background.html, fails as it says the view has no such function. Just to be clear, I'm trying to access a function within history.html AND pass a parameter to it (screenshotUrl).
EDIT: re Serg's suggestion I replaced the var addImage function in background with the following:
var port = chrome.tabs.connect(tab.id,{name: "history_connect"});
port.postMessage({mType:"url",url:screenshotUrl});
Then added a listener on the history page... worked!
I haven't used getViews() before so I can't comment on that (what does console say when you dump chrome.extension.getViews() into it?), but here is couple workarounds:
Pass your url as get parameter during tab creation (history.html?url=<urlencoded_url>)
Use requests. chrome.extension.sendRequest({url:url}); in bkgd page and chrome.extension.onRequest.addListener() in history.html
Use "pull" instead of "push". In history.html you can use chrome.extension.getBackgroundPage().getMyUrl()
I would use the first solution as it is the easiest and fastest.