Requirement:
All child windows which are opened and they are required to remain
open through out the user session on IE irrespective of user action
refreshes the browser windows.
Close all child windows when user click logoff action.
Problem:
Child window handle cannot be retained across the pages when browser re-render the window, due to F5/refresh button or navigation.
Solution:
Open each child window with identical name.
Save the assigned window name in local storage as item in collection or array [or in parent window.name that's the work around if local storage is not acceptable].
//Open popup window "ChildWinName1" from here
window.open("SomeSite/SomeApp/SomePage", "ChildWinName1", "width=600, height=400");
localStorage.setItem("Key1", "ChildWinName1");
//Open popup window "ChildWinName1" from here
window.open("SomeSite/SomeApp/SomePage", "ChildWinName2", "width=600, height=400");
localStorage.setItem("Key2", "ChildWinName2");
Create a blank page in your application which just has self.close method in script.
Page : BlankClose
<!DOCTYPE html>
<html>
<head>
<title>IndexX</title>
<script type="text/javascript">
function Exit() {
self.close();
}
this.Exit();
</script>
</head>
<body>
<div>
Bye..............
</div>
</body>
</html>
Upon logoff, iterate through the collection of window name, for each window name request the blank page[see 3.]. That will close each child window.
function closeAllChildWindow() {
var wins = localStorage.length
for (var i = 1; i <= wins; i++) {
var winName = localStorage.getItem("ChildWinName" + i.toString());
if (winName != null) {
window.open('/SomeSite/SomeApp/blankClose", "Home")', winName);
localStorage.removeItem("ChildWinName" + i.toString())
}
else {
if (localStorage.length > 0) wins++;
}
}
}
Note :
Instead of having multiple keys in local storage, JSON object can be used which has encapsulated string collection.
Related
I have a chrome extension which does the following:
When a user copies a word, a popup window opens with a specific url, searching the word in a dictionary. If the popup window already exists, it removes it and recreates it (if you ask why, the answer is: because chrome.windows.update() does not take URL as a parameter so I cannot simply update the window with a new URL).
The problem is: If the user is in another application (like MS Word) and copies a word, when the user clicks on the taskbar icon of the browser (chrome) popup window to bring it on the front, then Chrome does not paint the content of the page, it only displays the title of the page. If the user closes with the X button the popup window though, there is no problem. It happens only if the user just clicks back on MS Word to continue writing and then copies another word, without previously manually closing the popup window. The code is:
g_iIntervalID = setInterval(getClipboardText, 500);
function getClipboardText() {
g_oTA.select();
g_oBG.document.execCommand("Paste");
var clipText = g_oTA.value;
if (g_bOpenWindow) {
clipText = cleanWord(trim(clipText));
if (clipText != "" && clipText.length <= 64 && clipText != g_sPrevClipText && clipText != g_sWord) {
if (g_bClipFirstTime == false) {
g_sWord = clipText;
openLink();
}
g_sPrevClipText = clipText;
}
g_bClipFirstTime = false;
}
}
function openLink() {
chrome.windows.getAll(onWindowsQueryReply);
}
function onWindowsQueryReply(windows) {
var bWindowFound = false;
if (chrome.runtime.lastError) {
console.log(chrome.runtime.lastError);
} else {
if (g_iCreatedWindowID != 0 && windows.length > 0) {
var wnd;
for (var i = 0; i < windows.length; i++) {
wnd = windows[i];
if (g_iCreatedWindowID == wnd.id) {
bWindowFound = true;
var r = chrome.windows.remove(g_iCreatedWindowID, function() {
CreateWindow();
return;
});
}
}
}
if (bWindowFound === false) CreateWindow();
}
}
function CreateWindow() {
clearInterval(g_iResizeIntervalID);
var createData = {
state: "normal",
url: "https://www.example.com/search.php?word=" + g_sWord,
type: "popup",
top: g_iWinT,
left: g_iWinL,
height: g_iWinH,
width: g_iWinW
};
var creating = chrome.windows.create(createData, onWinCreated);
}
function onWinCreated(win) {
if (chrome.runtime.lastError) {
console.log(chrome.runtime.lastError);
} else {
g_iCreatedWindowID = win.id;
//console.log(g_iWinW + "#" + g_iWinH + "#" + g_iWinT + "#" + g_iWinL + "###The panel has been created"+JSON.stringify(win));
var updateData = {
state: "normal",
top: g_iWinT,
left: g_iWinL,
drawAttention: true,
focused: true
};
var updating = chrome.windows.update(win.id, updateData);
g_iResizeIntervalID = setInterval(getWindowSize, 200);
}
}
Steps:
User is using an app like MS Word
User double clicks a word and ctrl-c or right-click copies it.
When this happens then openLink() runs
The extension removes the current popup window (if it exists) and then creates a new one with a URL
A small icon for the new popup window appears flashing in the taskbar
The first time, the popup window comes automatically in front. The user reads then necessary information
The user clicks back on MS Word to continue work
The user marks another word and copies it
The extension opens another new popup window. This window for some reason does not come on front like the first time, but this is not the main problem. The user has to click its taskbar icon to bring it in front.
The user clicks the icon of the popup window in the taskbar in order to bring it to front.
The popup window comes to front, but it displays a blank page (except for the title).
Comments:
Chrome paints the contents ONLY if I click on the title bar and drag the window a bit OR if I hover the mouse on the icon of the pop up window in the taskbar so that a preview is displayed.
If the user closes the popup window with the X button, then the problem does not arise the next time he copies a word (plus the popup window goes automatically in front/focus, so none of the problems appears).
I have tried many things:
inserting async delays with setTimeout before creating and updating the pop window
repositioning and resizing the popup window in onWinCreated()
repositioning and resizing after the first chrome.windows.update()
But all these efforts in trying to trigger/force Chrome paint the window, have failed. Am I doing something wrong? How can I fix this issue? Also, why the first time when the popup opens, it comes automatically in front (or if I closed the previous popup manually)? But when it gets programmatically removed, it does not? Can this also be solved?
Thank you in advance
I have a site that builds the pages dynamically. It's a SharePoint site. The site contains a lot of document libraries. The libraries contain word, excel and PDF documents. When a user clicks on a document, the document opens in the client application for office documents only. PDFs simply open in the same window. when people close the window containing the document, they close the site. I'm trying to use javascript to onload add target="_blank" to the PDF links.
So far I have:
window.onload = function(){
l=document.links.length;
for(i = 0; i<l; i++) {
n = document.links[i].href.indexOf(".pdf");
if (n > 0){
document.links[i].setAttribute('target', '_blank');
}
}
}
This code sort of works as some of the pdf links load in a new window as expected, some load in the parent window and some links load in both a new window and the parent. How do I tell the browser not to load in the parent window and only in the new window?
This is what I want to achieve:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
</head>
<body>
a.pdf<br /><br />
b.html<br /><br />
c.pdf<br /><br />
<script>
window.onload = function(){
l=document.links.length;
for(i = 0; i<l; i++) {
n = document.links[i].href.indexOf(".pdf");
if (n > 0){
document.links[i].setAttribute('target', '_blank');
}
}
}
</script>
</body>
</html>
The problem I'm running into is that sharepoint document libraries are modifying the link behavior such that the javascript does not make then open in a new window. Below is an example of a link from a document library:
<a onfocus="OnLink(this)" href="https://rcd.sharepoint.com/HR/HR%20Policy%20Manual.pdf" onmousedown="return VerifyHref(this,event,'0','','')" onclick="return DispEx(this,event,'TRUE','FALSE','FALSE','','0','','','','','331','0','0','0x7fffffffffffffff','','')">HR Policy Manual</a>
If you don't have access to all elements for ahead with capturing all clicks on the page. Use addEventListener with enabled capturing for handling event. Test whether it's anchor tag and proceed to new page by own with code below:
document.addEventListener("click", function(e){
if (e.target.localName == 'a') {
var url = e.target.getAttribute('href');
e.stopPropagation();
// You can place extra checks here.
var tab = window.open(url, '_blank');
tab.focus();
}
}, true)
Do
Here is what I would do, I think I would collect the anchors and loop over them to check if the hrefs ends with .pdf and then add a function on all the .pdf links
Don't
Don't check for pdf files with .indexOf('.pdf'). Your check should fail If there's a filename called somedummyfile.pdf.something.png (which is a .png image) or any other formatted file.
Note that, new window might be blocked at user's end if they are using add-blockers.
Here is the Snippet:
function modifyLinks() {
let links = document.getElementsByTagName('a');
let properties = 'height=' + window.innerHeight + ',width=' + window.innerWidth + ',' + 'scrollbars=yes,status=yes';
for (i = 0; i < links.length; i++) {
if (links[i].href.endsWith('.pdf')) {
// links[i].setAttribute('target', '_blank'); // if you want to open them in new tab;
console.log(links[i].href);
links[i].addEventListener('click', function(e) {
e.preventDefault();
window.open(this.href, '_blank', properties);
})
}
}
}
window.addEventListener('load', modifyLinks);
File 1
File 2
File 3
HTML Link
Some Other file
I added the following JavaScript to get links containing "pdf" to open in a new window:
window.onload = function(){
l=document.links.length;
for(i = 0; i<l; i++) {
n = document.links[i].href.indexOf(".pdf");
if (n > 0){
document.links[i].setAttribute('target', '_blank');
}
}
}
I then noticed that document libraries were using a DispEx() javascript function on click of document links which negated the first bit of code. I had to overload the function with my own functionality.
function DispEx(a){
if (a.href.endsWith('.pdf')){
window.open(a);
return false;
}
}
Using both pieces of JavaScript in a content editor web part, I got PDF documents to open in a new window and all other links/documents to load in the same window.
I have a help link. If a user clicks on it, it opens a new window with fixed width and height. It's working well except that when I right click the link, there is either no options to 'open in a new tab' (in IE) or I can open in a new tab but is directed to an empty page (chrome). Can any one help to make this like a link and also by default open in a new window (not a tab)?
<html>
<head>
<title>
link
</title>
<script type="text/javascript">
function activateHelpView(helpUri) {
var WindowId = 'SomeWindowId';
var helpWindow = window.open(helpUri, WindowId, 'width=400,height=500,menubar=no,status=no,scrollbars=no,titlebar=no,toolbar=no,resizable=yes');
if (helpWindow) {
(helpWindow).focus();
}
}
</script>
</head>
<body>
<a id='PortOrderPageLearnMoreLink' href='javascript:' title='Learn more' onclick='activateHelpView("http://stackoverflow.com/")'>Learn more</a>
</body>
</html>
Use a real link, not the empty javascript: address. The onclick handler can prevent the link from doing anything "normal", but you'll have something for the right-click to work with.
target=_blank is a strong hint that you want the page opened in a new window, but whether that's honored at all -- and whether in a window or a tab -- is out of the page's control.
<script type="text/javascript">
function activateHelpView(helpUri) {
var WindowId = 'SomeWindowId';
var helpWindow = window.open(helpUri, WindowId, 'width=400,height=500,menubar=no,status=no,scrollbars=no,titlebar=no,toolbar=no,resizable=yes');
if (helpWindow) {
(helpWindow).focus();
}
}
</script>
<a id='PortOrderPageLearnMoreLink' href='http://stackoverflow.com/' title='Learn more' onclick='activateHelpView(this.href); return false;' target='_blank'>Learn more</a>
A more modern way of handling all of this -- particularly if there will be more than one help link -- is to add a class to all of them, and run some JavaScript to add the click handler to each in turn. The HTML stays clean (and with real links, still works if JavaScript is disabled or not loaded).
var helplinks = document.querySelectorAll('.helplink');
for (var i = 0; i < helplinks.length; ++i) {
helplinks[i].addEventListener('click', activateHelpView);
}
function activateHelpView(event) {
event.stopPropagation(); // don't let the click run its course
event.preventDefault();
var helpUri = this.href; // "this" will be the link that was clicked
var WindowId = 'SomeWindowId';
var helpWindow = window.open(helpUri, WindowId, 'width=400,height=500,menubar=no,status=no,scrollbars=no,titlebar=no,toolbar=no,resizable=yes');
if (helpWindow) {
helpWindow.focus();
}
}
<a id='PortOrderPageLearnMoreLink'
href='http://stackoverflow.com/' title='Learn more'
class='helplink' target='_blank'>Learn more</a>
StackOverflow snippets aren't allowed to use some of these functions. A working example can be found here.
I have a javascript code which opens a new tab in browser from a list each 50seconds, but the browser will crash after 50tabs or more.
so I want to close new tab and open another one each 50 seconds.
my code is:
<html>
<head>
<script>
function openWindow(){
window.open('"about:blank"');
var x = document.getElementById('a').value.split('\n');
atTime = 0;
for (var i = 0; i < x.length; i++) {
if (x[i].indexOf('.') > 0) {
site = x[i];
if (x[i].indexOf('://') < 0) { site = 'http://' + x[i]; }
setTimeout("window.open('" + site + "')", atTime);
atTime += 50000;
}
}
}
</script>
<style>
html, body
{
height : 99%;
width : 99%;
}
textarea
{
height : 80%;
width : 90%;
}
</style>
</head>
<body>
<textarea id="a"></textarea>
<br>
<input type="button" value="Open Windows" onClick="openWindow()">
<input type="button" value="Clear" onClick="document.getElementById('a').value=''">
</body>
</html>
window.open returns a reference to the new window. Call close on that handle.
https://developer.mozilla.org/en-US/docs/Web/API/window.close
note btw:
FAQ
How can I prevent the confirmation message asking the user whether he wants to close the window?
You can not. New windows not opened by javascript can not as a rule be closed by JavaScript. The JavaScript Console in Mozilla-based browsers will report the warning message: "Scripts may not close windows that were not opened by script." Otherwise the history of URLs visited during the browser session would be lost.
window.close() should work to close tabs you opened (but it's not possible to close a tab you didn't open)
in fact it can't be closed unless it was opened by a script but there is a way to fool the browser into thinking that's the case:
window.open('','_parent','');
then you can use
window.close();
Putting it together:
<script language="javascript" type="text/javascript">
function closeWindow() {
window.open('','_parent','');
window.close();
}
</script>
reference: http://www.yournewdesigner.com/css-experiments/javascript-window-close-firefox.html
to close a firefox tab use
window.close()
this will close the current window.
I need to pass some text from the current page to a popup window without going for a server hit. The information (herewith represented by 90) is already available in the parent form (it's like a paragraph-long text which is stored in a hidden variable). I just need to display that as a popup.
Here's what I've tried, this works to some extent but doesn't work if I pass text, instead of a number. My second concern is that the solution kinda looks ugly. Any tips? Thank you.
This is SCCE, you can run it straight in your machine.
<html>
<head>
<title>A New Window</title>
<script type="text/javascript">
var newWindow;
var data;
function makeNewWindow(param) {
data = param;
if (!newWindow || newWindow.closed) {
newWindow = window.open("","sub","status,height=200,width=300");
setTimeout("writeToWindow()", 50); /* wait a bit to give time for the window to be created */
} else if (newWindow.focus) {
newWindow.focus( ); /* means window is already open*/
}
}
function writeToWindow() {
var k = data;
alert(data);
var newContent = "<html><head><title>Additional Info</title></head>";
newContent += "<body><h1>Some Additional Info</h1>";
newContent += "<scr"+"ipt type='text/javascript' language='javascript'> var localVar; localVar = "+ k +"; document.write('localVar value: '+localVar);</scr"+"ipt>";
newContent += "</body></html>";
// write HTML to new window document
newWindow.document.write(newContent);
newWindow.document.close( ); // close layout stream
}
</script>
</head>
<body>
<form>
<input type="button" value="Create New Window" onclick="makeNewWindow('90');" />
</form>
</body>
</html>
Actually, I googled and saw some other approach that uses window.opener.document.forms.element, but here, the window has to know in advance what it has to read from the parent. I need to be able to pass it as it will vary:
<textarea rows="15" name="projectcontent" id="projectcontent" cols="87"></textarea>
<b>View Content</b>
<head>
<title>View Project Content</title>
</head>
<body>
<img src="/images/toplogo.jpg"><br/>
<script language="Javascript">
document.write(window.opener.document.forms['yourformname'].elements['projectcontent'].value)
</script>
<img src="/images/bottomlogo.jpg">
</body>
</html>
use window.opener
From Mozilla Developer Network:
When a window is opened from another window, it maintains a reference
to that first window as window.opener. If the current window has no
opener, this method returns NULL.
https://developer.mozilla.org/en-US/docs/Web/API/window.opener
This way you can have on your original window a callback, and you can notify the window it's load and ready, rather than wait a random delay...
you add a function on the original window:
window.popupReady = function (callbackToPopup) {
callbackToPopup(newData);
}
then the popup can tell the parent window it's ready and pass it a callback to update it with data..
and on the popup try something like:
window.dataReady(newData)
{
alert(newData);
}
document.addEventListener("load", function() { window.opener.popupReady (dataReady); }
I didn't test this code, but I would take such a path as this should ensure the popupWindow is ready for you and is along the spirit of JavaScript.
In your onclick attribute you pass '90' to the function, but the function isn't set up to take an argument. So, change the first line of your function like this:
function writeToWindow(data) {
You don't need the global var data; or the local var k = data;, so get rid of them.
And instead of + k + write + data +.
That should do get your data passed.
Use this code, it works perfectly in all browsers .
#desc = parent text area id
#desc_textarea = popup
$("#desc_textarea").val(window.opener.$("#desc").val())