focus child window from another child window - javascript

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.

Related

Cannot trigger a script in a pop-up window

I will edit this main post to update with the latest code and avoid confusing.
The problem is that Im popping up a new window with a button, but this new window is not making a script work even if its being loaded in the HTML code.
To make this easier, I just added a window.alert to the script that should be working into the new window, and its never showing.
This is what we use to pop up the new window (actually working and popping up the new window properly)
jQuery(document).ready(function( $ ){
$("#imprimirPdf").live("click", function () {
var divContents = $("#cartaDeAmor").html();.
var printWindow = window.open('', '', 'height=400,width=800')
printWindow.document.write('<!DOCTYPE html>');
printWindow.document.write('<html>');
printWindow.document.write('<head>');
printWindow.document.write('<script type="text/javascript" src="http://www.mywebsiteurl.com/descargarPDF.js"><\/script>'); // <-- Loading the script that is not working.
printWindow.document.write('<script type="text/javascript" src="http://www.mywebsiteurl.com/html2pdf.bundle.min.js"><\/script>');
printWindow.document.write('</head>');
printWindow.document.write('<body>');
printWindow.document.write('<div id="carta">Content</div>');
printWindow.document.write('<input type="button" value="Function trigger test" onclick="eKoopman2();">'); // Calling the function
printWindow.document.write('<script>')
printWindow.document.write('(function() { eKoopman2(); })();'); // Calling the function again
printWindow.document.write('<\/script>')
printWindow.document.write('</body>')
printWindow.document.write('</html>');
printWindow.document.close();
});
});
This can be found at "descargarPDF.js" (the script that I need to be loaded)
function eKoopman2() {
var element = document.getElementById('carta');
html2pdf(element);
window.alert("sometext");
}
This is what we find in the HTML code
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="http://www.mywebsiteurl.com/descargarPDF.js"></script>
<script type="text/javascript" src="http://www.mywebsiteurl.com/html2pdf.bundle.min.js"></script>
</head>
<body>
<div id="carta">Content to be exported</div>
<input type="button" value="Function trigger test" onclick="eKoopman2();">
<script>(function() { eKoopman2(); })();</script>
</body>
</html>
And the problem is that the alert loaded in the script is never showing. Not working in the button click and not working in the self called function.

Modal dialog box does not communicate with main HTA window

I have a javascript in an HTA which looks like this:
var result = null;
window.showModalDialog("dialog.hta", window, "dialogHeight:300px; dialogWidth:300px");
alert(result);
dialog.hta:
<html>
<head>
<title>Dialog box</title>
<meta http-equiv="MSThemeCompatible" content="yes"/>
</head>
<body style="background:#F0F0F0">
<select id="colors">
<option selected>Red</option>
<option>Blue</option>
<option>Green</option>
<option>Yellow</option>
</select><br/>
<script type="text/javascript">
function ok(){
window.dialogArguments.result = colors.getElementsByTagName("option")[colors.selectedIndex].innerHTML;
window.close();
}
</script>
<button onclick="ok()">OK</button>
<button onclick="window.close()">Cancel</button>
</body>
</html>
The problem is that when I press OK the alert(result) in the main HTA window always says null, even when I click on the OK button in the modal dialog box.
How can I do so that it says which option the user selects in the list when the OK button is pressed and null when the cancel button is pressed?
This is how modal dialog works:
In the main app:
// Call a dialog, and store the returned value to a variable
var result = showModalDialog(path, argument, options);
On dialog close:
// Set the returnValue
var elem = document.getElementById("colors");
window.returnValue = elem[elem.selectedIndex].text;
top.close();
After setting the returnValue in the dialog, you can read it from result after the dialog has been closed.
option elements didn't have innerHTML in old IEs, hence you've to use text property instead. You can also add a value attribute to the select element, and then create a return value in a simple way:
window.returnValue = document.getElementById('colors').value;

Open multiple links in Chrome at once as new tabs

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.

Link not showing in dropbox chooser app

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>

Access function from background page in Chrome extension

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.

Categories

Resources