Display data on different browser tabs - javascript

The browser has two tabs opened with the different URL.
The data received by one html page from server...
Is it possible to display the same data in another tab which is already opened without reloading...If so how should that has to be done...

Yes, if either:
Your code opened the other tab (via window.open), or
The window has a name (such as one assigned via the target attribute on a link, e.g. target="otherwindow")
Additionally, the window's content must be on the same origin as the document you're interacting with it from, or you'll be blocked by the Same Origin Policy.
1. If you're opening it via window.open
window.open returns a reference to the window object for the window that was opened, which (assuming it's on the same origin) you can do things with. E.g.:
var wnd = window.open("/some/url");
// ...later, when it's loaded...
var div = wnd.document.createElement('div');
div.innerHTML = "content";
wnd.document.appendChild(div);
You can use all of the usual DOM methods. If you load a library in the other window, you can use that as well. (It's important to understand that the two windows have two different global namespaces, they're not shared.)
Here's a full example. I used jQuery in the below just for convenience, but jQuery is not required for this. As I said above, you can use the DOM directly (or another library if you like):
Live Copy | Live Source
HTML:
<button id="btnOpen">Open Window</button>
<button id="btnAdd">Add Content</button>
<button id="btnRemove">Remove Content</button>
JavaScript:
(function($) {
var btnOpen,
btnAdd,
btnRemove,
wnd,
wndTimeout,
wnd$,
newContentId = 0;
btnOpen = $("#btnOpen");
btnAdd = $("#btnAdd");
btnRemove = $("#btnRemove");
updateButtons();
btnOpen.click(openWindow);
btnAdd.click(addContent);
btnRemove.click(removeContent);
function updateButtons() {
btnOpen[0].disabled = !!wnd;
btnAdd[0].disabled = !wnd$;
btnRemove[0].disabled = !wnd$;
}
function openWindow() {
if (!wnd) {
display("Opening window");
wnd$ = undefined;
wndTimeout = new Date().getTime() + 10000;
wnd = window.open("/etogel/1");
updateButtons();
checkReady();
}
}
function windowClosed() {
display("Other window was closed");
wnd = undefined;
wnd$ = undefined;
updateButtons();
}
function checkReady() {
if (wnd && wnd.jQuery) {
wnd$ = wnd.jQuery;
wnd$(wnd).on("unload", windowClosed);
updateButtons();
}
else {
if (new Date().getTime() > wndTimeout) {
display("Timed out waiting for other window to be ready");
wnd = undefined;
}
else {
setTimeout(checkReady, 10);
}
}
}
function addContent() {
var div;
if (wnd$) {
++newContentId;
display("Adding content '" + newContentId + "'");
wnd$("<div>").addClass("ourcontent").html("Added content block #" + newContentId).appendTo(wnd.document.body);
}
}
function removeContent() {
var div;
if (wnd$) {
div = wnd$("div.ourcontent").first();
if (div[0]) {
display("Removing div '" + div.html() + "' from other window");
div.remove();
}
else {
display("None of our content divs found in other window, not removing anything");
}
}
}
function display(msg) {
$("<p>").html(String(msg)).appendTo(document.body);
}
})(jQuery);
2. If you're opening it via a link with target
window.open can find and return a reference to that window:
var wnd = window.open("", "otherwindow");
Note that the URL argument is empty, but we pass it the name from the target attribute. The window must already be open for this to work (otherwise it will open a completely blank window).
Here's the above example, modified to assume you've opened the window via ...:
Live Copy | Live Source
HTML:
Click to open the other window
<br><button id="btnGet">Get Window</button>
<button id="btnAdd">Add Content</button>
<button id="btnRemove">Remove Content</button>
JavaScript:
(function($) {
var btnGet,
btnAdd,
btnRemove,
wnd,
wndTimeout,
wnd$,
newContentId = 0;
btnGet = $("#btnGet");
btnAdd = $("#btnAdd");
btnRemove = $("#btnRemove");
updateButtons();
btnGet.click(getWindow);
btnAdd.click(addContent);
btnRemove.click(removeContent);
function updateButtons() {
btnGet[0].disabled = !!wnd;
btnAdd[0].disabled = !wnd$;
btnRemove[0].disabled = !wnd$;
}
function getWindow() {
if (!wnd) {
display("Getting 'otherwindow' window");
wnd$ = undefined;
wndTimeout = new Date().getTime() + 10000;
wnd = window.open("", "otherwindow");
updateButtons();
checkReady();
}
}
function windowClosed() {
display("Other window was closed");
wnd = undefined;
wnd$ = undefined;
updateButtons();
}
function checkReady() {
if (wnd && wnd.jQuery) {
wnd$ = wnd.jQuery;
wnd$(wnd).on("unload", windowClosed);
updateButtons();
}
else {
if (new Date().getTime() > wndTimeout) {
display("Timed out looking for other window");
wnd = undefined;
updateButtons();
}
else {
setTimeout(checkReady, 10);
}
}
}
function addContent() {
var div;
if (wnd$) {
++newContentId;
display("Adding content '" + newContentId + "'");
wnd$("<div>").addClass("ourcontent").html("Added content block #" + newContentId).appendTo(wnd.document.body);
}
}
function removeContent() {
var div;
if (wnd$) {
div = wnd$("div.ourcontent").first();
if (div[0]) {
display("Removing div '" + div.html() + "' from other window");
div.remove();
}
else {
display("None of our content divs found in other window, not removing anything");
}
}
}
function display(msg) {
$("<p>").html(String(msg)).appendTo(document.body);
}
})(jQuery);

Related

how to call function in parent window when closing child window

I have a parent window and a child window. I want to call a function when closing the child window .
The code of parent window is below:
function Button4_onclick(){
newWin=window.open("http://10.10.19.22:8086/childwindow.jsp");
newWin.onunload = updatet();
}
function updatet()
{
if(newWin.location != "about:blank"){
document.getElementById("SerialNumber24").value='2345';
}
But this code not work and the function is called when opening the child window instead. So which event listener can I use for closing ? Thx.
That is possible if you own the child window. You need to set event onbeforeunload on the child.
Working fiddle: https://jsfiddle.net/itgoldman/9mafwu2L/33/
window.foo = function foo() {
alert("hello i am parent")
}
function open_window() {
var win = window.open("", "Title", "toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=yes,resizable=yes,width=600,height=200,top=" + (screen.height - 400) + ",left=" + (screen.width - 840));
if (!win) {
alert("window open was blocked");
return;
}
win.document.write(str);
win.window.parent = this;
}
var script = `
window.onbeforeunload = function(ev) {
window.parent.foo();
return;
}
`;
var str = '<scri' + 'pt>' + script + '</scr' + 'ipt><h1>close me</h1>'

How to make window.open popup as a dialog

I have this button here actual It is made of aspx.net html. When I click this button I wanted to popup a modal. Making modal is easy to do, but in my case I wanted to call another web page(Printer.aspx) of my server.
<td>
<Button ID="btnPrint" runat="server" OnClick="Printer_Click" >Printer</Button>
</td>
Here is js code. With this code I was able to open new window as a popup but I wanted to call Printer.aspx in my show modaldiv
//Printer button click function
function Printer_OnClientClick(){
var returnValue = showPopUp('Printer.aspx', 700, 500);
if (returnValue != null) {
return true;
}
return false;
}
//showPopUp function
function showPopUp(url,winName,w,h,scroll, clientID){
LeftPosition = (screen.width) ? (screen.width-w)/2 : 0;
TopPosition = (screen.height) ? (screen.height-h)/2 : 0;
settings ='height='+h+',width='+w+',top='+TopPosition+',left='+LeftPosition+',scrollbars='+scroll+',resizable'
if (url.indexOf("?") == -1)
{
url = url + "?";
}else {
url = url + "&";
}
url = url + "PageId=" + $('#hiddenPageDataId').val();
var timstamp= new Date().getTime();
url = url + "&timstamp=" + timstamp;
try {
popupWindow = window.open(url,winName,settings) // This will open new tab
} catch(e) {
popupWindow = null;
}
if (clientID== null){
return popupWindow;
} else {
if (popupWindow != null) {
$('#' + clientID).val(popupWindow);
}
return false;
}
}
Please do not get confused this Js is which I made to do window.open(), but now I wanted to call the next page in modal iframe.
I also have another js which I discovered in Google here it is:
$(document).ready(function () {
$(".PrinterSelect").click(function () {
$("#iFrameDialog").attr('src', $(this).attr("href"));
$("#divDialog").dialog({
width: 400,
height: 450,
modal: true,
close: function () {
$("#iFrameDialog").attr('src', "about:blank");
}
});
return false;
});
});
This will work in html page, but I wanted to do it with an aspx page.

Detect URL if it is already opened and throw pop-up : HTML+JS [duplicate]

I want to check with JavaScript if the user has already opened my website in another tab in their browser.
It seems I cannot do that with pagevisibility...
The only way I see is to use WebSocket based on a session cookie, and check if the client has more than one socket. But by this way, from current tab, I have to ask my server if this user has a tab opened right next to their current browser tab. It is a little far-fetched!
Maybe with localstorage?
The shorter version with localStorage and Storage listener
<script type="text/javascript">
// Broadcast that you're opening a page.
localStorage.openpages = Date.now();
var onLocalStorageEvent = function(e){
if(e.key == "openpages"){
// Listen if anybody else is opening the same page!
localStorage.page_available = Date.now();
}
if(e.key == "page_available"){
alert("One more page already open");
}
};
window.addEventListener('storage', onLocalStorageEvent, false);
</script>
Update:
Works on page crash as well.
Stimulate page crash in chrome: chrome://inducebrowsercrashforrealz
Live demo
Using local storage I created a simple demo that should accomplish what your looking to do. Basically, it simply maintains a count of currently opened windows. When the window is closed the unload events fire and remove it from the total window count.
When you first look at it, you may think there's more going on than there really is. Most of it was a shotty attempt to add logic into who was the "main" window, and who should take over as the "main" window as you closed children. (Hence the setTimeout calls to recheck if it should be promoted to a main window) After some head scratching, I decided it would take too much time to implement and was outside the scope of this question. However, if you have two windows open (Main, and Child) and you close the Main, the child will be promoted to a main.
For the most part you should be able to get the general idea of whats going on and use it for your own implementation.
See it all in action here:
http://jsbin.com/mipanuro/1/edit
Oh yeah, to actually see it in action... Open the link in multiple windows. :)
Update:
I've made the necessary changes to have the the local storage maintain the "main" window. As you close tabs child windows can then become promoted to a main window. There are two ways to control the "main" window state through a parameter passed to the constructor of WindowStateManager. This implementation is much nicer than my previous attempt.
JavaScript:
// noprotect
var statusWindow = document.getElementById('status');
(function (win)
{
//Private variables
var _LOCALSTORAGE_KEY = 'WINDOW_VALIDATION';
var RECHECK_WINDOW_DELAY_MS = 100;
var _initialized = false;
var _isMainWindow = false;
var _unloaded = false;
var _windowArray;
var _windowId;
var _isNewWindowPromotedToMain = false;
var _onWindowUpdated;
function WindowStateManager(isNewWindowPromotedToMain, onWindowUpdated)
{
//this.resetWindows();
_onWindowUpdated = onWindowUpdated;
_isNewWindowPromotedToMain = isNewWindowPromotedToMain;
_windowId = Date.now().toString();
bindUnload();
determineWindowState.call(this);
_initialized = true;
_onWindowUpdated.call(this);
}
//Determine the state of the window
//If its a main or child window
function determineWindowState()
{
var self = this;
var _previousState = _isMainWindow;
_windowArray = localStorage.getItem(_LOCALSTORAGE_KEY);
if (_windowArray === null || _windowArray === "NaN")
{
_windowArray = [];
}
else
{
_windowArray = JSON.parse(_windowArray);
}
if (_initialized)
{
//Determine if this window should be promoted
if (_windowArray.length <= 1 ||
(_isNewWindowPromotedToMain ? _windowArray[_windowArray.length - 1] : _windowArray[0]) === _windowId)
{
_isMainWindow = true;
}
else
{
_isMainWindow = false;
}
}
else
{
if (_windowArray.length === 0)
{
_isMainWindow = true;
_windowArray[0] = _windowId;
localStorage.setItem(_LOCALSTORAGE_KEY, JSON.stringify(_windowArray));
}
else
{
_isMainWindow = false;
_windowArray.push(_windowId);
localStorage.setItem(_LOCALSTORAGE_KEY, JSON.stringify(_windowArray));
}
}
//If the window state has been updated invoke callback
if (_previousState !== _isMainWindow)
{
_onWindowUpdated.call(this);
}
//Perform a recheck of the window on a delay
setTimeout(function()
{
determineWindowState.call(self);
}, RECHECK_WINDOW_DELAY_MS);
}
//Remove the window from the global count
function removeWindow()
{
var __windowArray = JSON.parse(localStorage.getItem(_LOCALSTORAGE_KEY));
for (var i = 0, length = __windowArray.length; i < length; i++)
{
if (__windowArray[i] === _windowId)
{
__windowArray.splice(i, 1);
break;
}
}
//Update the local storage with the new array
localStorage.setItem(_LOCALSTORAGE_KEY, JSON.stringify(__windowArray));
}
//Bind unloading events
function bindUnload()
{
win.addEventListener('beforeunload', function ()
{
if (!_unloaded)
{
removeWindow();
}
});
win.addEventListener('unload', function ()
{
if (!_unloaded)
{
removeWindow();
}
});
}
WindowStateManager.prototype.isMainWindow = function ()
{
return _isMainWindow;
};
WindowStateManager.prototype.resetWindows = function ()
{
localStorage.removeItem(_LOCALSTORAGE_KEY);
};
win.WindowStateManager = WindowStateManager;
})(window);
var WindowStateManager = new WindowStateManager(false, windowUpdated);
function windowUpdated()
{
//"this" is a reference to the WindowStateManager
statusWindow.className = (this.isMainWindow() ? 'main' : 'child');
}
//Resets the count in case something goes wrong in code
//WindowStateManager.resetWindows()
HTML:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>JS Bin</title>
</head>
<body>
<div id='status'>
<span class='mainWindow'>Main Window</span>
<span class='childWindow'>Child Window</span>
</div>
</body>
</html>
CSS:
#status
{
display:table;
width:100%;
height:500px;
border:1px solid black;
}
span
{
vertical-align:middle;
text-align:center;
margin:0 auto;
font-size:50px;
font-family:arial;
color:#ba3fa3;
display:none;
}
#status.main .mainWindow,
#status.child .childWindow
{
display:table-cell;
}
.mainWindow
{
background-color:#22d86e;
}
.childWindow
{
background-color:#70aeff;
}
(2021) You can use BroadcastChannel to communicate between tabs of the same origin.
For example, put the following at the top level of your js code, then test by opening 2 tabs:
const bc = new BroadcastChannel("my-awesome-site");
bc.onmessage = (event) => {
if (event.data === `Am I the first?`) {
bc.postMessage(`No you're not.`);
alert(`Another tab of this site just got opened`);
}
if (event.data === `No you're not.`) {
alert(`An instance of this site is already running`);
}
};
bc.postMessage(`Am I the first?`);
I know it is late, but maybe help someone
This snippet of code, will detect how many tabs are open and how many are active (visible) and if none of tabs is active, it will choose last opened tab, as active one.
This code will handle windows/tab crash too and it will refresh the count at crash.
Because localStorage is not supported on Stack Overflow currently, please test here.
<html>
<body>
Open in several tabs or windows
<div id="holder_element"></div>
<script type="text/javascript">
//localStorage.clear();
manage_crash();
//Create a windows ID for each windows that is oppened
var current_window_id = Date.now() + "";//convert to string
var time_period = 3000;//ms
//Check to see if PageVisibility API is supported or not
var PV_API = page_visibility_API_check();
/************************
** PAGE VISIBILITY API **
*************************/
function page_visibility_API_check ()
{
var page_visibility_API = false;
var visibility_change_handler = false;
if ('hidden' in document)
{
page_visibility_API = 'hidden';
visibility_change_handler = 'visibilitychange';
}
else
{
var prefixes = ['webkit','moz','ms','o'];
//loop over all the known prefixes
for (var i = 0; i < prefixes.length; i++){
if ((prefixes[i] + 'Hidden') in document)
{
page_visibility_API = prefixes[i] + 'Hidden';
visibility_change_handler = prefixes[i] + 'visibilitychange';
}
}
}
if (!page_visibility_API)
{
//PageVisibility API is not supported in this device
return page_visibility_API;
}
return {"hidden": page_visibility_API, "handler": visibility_change_handler};
}
if (PV_API)
{
document.addEventListener(PV_API.handler, function(){
//console.log("current_window_id", current_window_id, "document[PV_API.hidden]", document[PV_API.hidden]);
if (document[PV_API.hidden])
{
//windows is hidden now
remove_from_active_windows(current_window_id);
//skip_once = true;
}
else
{
//windows is visible now
//add_to_active_windows(current_window_id);
//skip_once = false;
check_current_window_status ();
}
}, false);
}
/********************************************
** ADD CURRENT WINDOW TO main_windows LIST **
*********************************************/
add_to_main_windows_list(current_window_id);
//update active_window to current window
localStorage.active_window = current_window_id;
/**************************************************************************
** REMOVE CURRENT WINDOWS FROM THE main_windows LIST ON CLOSE OR REFRESH **
***************************************************************************/
window.addEventListener('beforeunload', function ()
{
remove_from_main_windows_list(current_window_id);
});
/*****************************
** ADD TO main_windows LIST **
******************************/
function add_to_main_windows_list(window_id)
{
var temp_main_windows_list = get_main_windows_list();
var index = temp_main_windows_list.indexOf(window_id);
if (index < 0)
{
//this windows is not in the list currently
temp_main_windows_list.push(window_id);
}
localStorage.main_windows = temp_main_windows_list.join(",");
return temp_main_windows_list;
}
/**************************
** GET main_windows LIST **
***************************/
function get_main_windows_list()
{
var temp_main_windows_list = [];
if (localStorage.main_windows)
{
temp_main_windows_list = (localStorage.main_windows).split(",");
}
return temp_main_windows_list;
}
/**********************************************
** REMOVE WINDOWS FROM THE main_windows LIST **
***********************************************/
function remove_from_main_windows_list(window_id)
{
var temp_main_windows_list = [];
if (localStorage.main_windows)
{
temp_main_windows_list = (localStorage.main_windows).split(",");
}
var index = temp_main_windows_list.indexOf(window_id);
if (index > -1) {
temp_main_windows_list.splice(index, 1);
}
localStorage.main_windows = temp_main_windows_list.join(",");
//remove from active windows too
remove_from_active_windows(window_id);
return temp_main_windows_list;
}
/**************************
** GET active_windows LIST **
***************************/
function get_active_windows_list()
{
var temp_active_windows_list = [];
if (localStorage.actived_windows)
{
temp_active_windows_list = (localStorage.actived_windows).split(",");
}
return temp_active_windows_list;
}
/*************************************
** REMOVE FROM actived_windows LIST **
**************************************/
function remove_from_active_windows(window_id)
{
var temp_active_windows_list = get_active_windows_list();
var index = temp_active_windows_list.indexOf(window_id);
if (index > -1) {
temp_active_windows_list.splice(index, 1);
}
localStorage.actived_windows = temp_active_windows_list.join(",");
return temp_active_windows_list;
}
/********************************
** ADD TO actived_windows LIST **
*********************************/
function add_to_active_windows(window_id)
{
var temp_active_windows_list = get_active_windows_list();
var index = temp_active_windows_list.indexOf(window_id);
if (index < 0)
{
//this windows is not in active list currently
temp_active_windows_list.push(window_id);
}
localStorage.actived_windows = temp_active_windows_list.join(",");
return temp_active_windows_list;
}
/*****************
** MANAGE CRASH **
******************/
//If the last update didn't happened recently (more than time_period*2)
//we will clear saved localStorage's data and reload the page
function manage_crash()
{
if (localStorage.last_update)
{
if (parseInt(localStorage.last_update) + (time_period * 2) < Date.now())
{
//seems a crash came! who knows!?
//localStorage.clear();
localStorage.removeItem('main_windows');
localStorage.removeItem('actived_windows');
localStorage.removeItem('active_window');
localStorage.removeItem('last_update');
location.reload();
}
}
}
/********************************
** CHECK CURRENT WINDOW STATUS **
*********************************/
function check_current_window_status(test)
{
manage_crash();
if (PV_API)
{
var active_status = "Inactive";
var windows_list = get_main_windows_list();
var active_windows_list = get_active_windows_list();
if (windows_list.indexOf(localStorage.active_window) < 0)
{
//last actived windows is not alive anymore!
//remove_from_main_windows_list(localStorage.active_window);
//set the last added window, as active_window
localStorage.active_window = windows_list[windows_list.length - 1];
}
if (! document[PV_API.hidden])
{
//Window's page is visible
localStorage.active_window = current_window_id;
}
if (localStorage.active_window == current_window_id)
{
active_status = "Active";
}
if (active_status == "Active")
{
active_windows_list = add_to_active_windows(current_window_id);
}
else
{
active_windows_list = remove_from_active_windows(current_window_id);
}
console.log(test, active_windows_list);
var element_holder = document.getElementById("holder_element");
element_holder.insertAdjacentHTML("afterbegin", "<div>"+element_holder.childElementCount+") Current Windows is "+ active_status +" "+active_windows_list.length+" window(s) is visible and active of "+ windows_list.length +" windows</div>");
}
else
{
console.log("PageVisibility API is not supported :(");
//our INACTIVE pages, will remain INACTIVE forever, you need to make some action in this case!
}
localStorage.last_update = Date.now();
}
//check storage continuously
setInterval(function(){
check_current_window_status ();
}, time_period);
//initial check
check_current_window_status ();
</script>
</body>
</html>

window.document in IE

I have this js to show a popup:
oauthpopup.js:
popup.show = function(options) {
this.destination_ = options.destination;
this.windowOptions_ = options.windowOptions;
this.closeCallback_ = options.closeCallback;
this.win_ = null;
this.win_ = window.open(this.destination_, "_blank", this.windowOptions_);
if (this.win_) {
// Poll every 100ms to check if the window has been closed
var self = this;
var closure = function() {
self.checkClosed_();
};
this.timer_ = window.setInterval(closure, 100);
}
return false;
};
popup.checkClosed_ = function() {
if ((!this.win_) || this.win_.closed) {
this.handleApproval_();
}
};
popup.handleApproval_ = function() {
if (this.timer_) {
window.clearInterval(this.timer_);
this.timer_ = null;
}
if (this.win_) {
this.win_.close();
//this.win_ = null;
}
try {
console.log(this.win_.document);
if (this.win_.document.scripts[0].innerHTML === 'window.close();') {
this.closeCallback_();
};
} catch (ex) { }
this.win_ = null;
return false;
};
page script
popup.show({destination: '/auth/' + channel, windowOptions: 'location=0,status=0',
closeCallback:function() {
switchView(divToShow);
}
});
function switchView(divtoShow) {
$("#" + divtoShow).addClass("hidden");
$("#" + divtoShow).removeClass("hidden");
};
It works perfectly in Chrome and Firefox, but in IE this line: this.win_.document.scripts[0].innerHTML doesn't works, I put this in a alert() but nothing happens.
EDIT:
The script tag 'window.close();' is rendered from rails controller in a html page.
The html page close the popup when is rendered, the popup is for twitter and google authentication.
How I can execute the callback after the page is rendered and it is closed?

Set title in the window popup

Is it possible to set a title in the window popup?
I have this in javascript:
var popup = window.open('......');
popup.document.title = "my title";
but this does not work..still can't see any title
EDIT: the page popup is displaying is .aspx and it HAS a title tag, but still can't see that on the popup window..
Since popup.onload does not seem to work, here is a workaround: http://jsfiddle.net/WJdbk/.
var win = window.open('', 'foo', ''); // open popup
function check() {
if(win.document) { // if loaded
win.document.title = "test"; // set title
} else { // if not loaded yet
setTimeout(check, 10); // check in another 10ms
}
}
check(); // start checking
I was having problems with the accepted answer until I realized that if you open an existing, slow page that already has a <title> the browser will 1) set your title, then 2) once the document fully loads it will (re)set the popup title with the "normal" value.
So, introducing a reasonable delay (function openPopupWithTitle):
var overridePopupTitle = function(popup, title, delayFinal, delayRepeat) {
// https://stackoverflow.com/a/7501545/1037948
// delay writing the title until after it's fully loaded,
// because the webpage's actual title may take some time to appear
if(popup.document) setTimeout(function() { popup.document.title = title; }, delayFinal || 1000);
else setTimeout(function() { overridePopupTitle(popup, title); }, delayRepeat || 100);
}
var openPopupWithTitle = function(url, title, settings, delay) {
var win = window.open(url, title, settings);
overridePopupTitle(win, title, delay);
return win;
}
None of these answers worked for me. I was trying to open a popup with a PDF inside and kept getting permission denied trying to set the title using the above methods. I finally found another post that pointed me in the correct direction. Below is the code I ended up using.
Source: How to Set the Title in Window Popup When Url Points to a PDF File
var winLookup;
var showToolbar = false;
function openReportWindow(m_title, m_url, m_width, m_height)
{
var strURL;
var intLeft, intTop;
strURL = m_url;
// Check if we've got an open window.
if ((winLookup) && (!winLookup.closed))
winLookup.close();
// Set up the window so that it's centered.
intLeft = (screen.width) ? ((screen.width - m_width) / 2) : 0;
intTop = (screen.height) ? ((screen.height - m_height) / 2) : 0;
// Open the window.
winLookup = window.open('', 'winLookup','scrollbars=no,resizable=yes,toolbar='+(showToolbar?'yes':'no')+',height=' + m_height + ',width=' + m_width + ',top=' + intTop + ',left=' + intLeft);
checkPopup(m_url, m_title);
// Set the window opener.
if ((document.window != null) && (!winLookup.opener))
winLookup.opener = document.window;
// Set the focus.
if (winLookup.focus)
winLookup.focus();
}
function checkPopup(m_url, m_title) {
if(winLookup.document) {
winLookup.document.write('<html><head><title>' + m_title + '</title></head><body height="100%" width="100%"><embed src="' +m_url + '" type="application/pdf" height="100%" width="100%" /></body></html>');
} else {
// if not loaded yet
setTimeout(checkPopup(m_url, m_title), 10); // check in another 10ms
}
}
You can use also
var popup = window.open('......');
popup.onload = function () {
popup.document.title = "my title";
}
Not sure if this will help,
function GetInput() {
var userInput;
var stringOutput;
userInput = prompt('What should the title be?', "");
stringOutput = userInput;
document.title = stringOutput;
}
<button type="button" onclick="GetInput()">Change Title</button>
var win= window.open('......');
win.document.writeln("<title>"+yourtitle+"</title>");
This works for me, tested in chromium browsers.
I ended up creating a setTitle method in my popup window and calling it from my parent page.
//popup page:
function setTitle(t) {
document.title = t;
}
//parent page
popupWindow.setTitle('my title');
Try this, it will work.
var timerObj, newWindow;
function openDetailsPopUpWindow(url) {
newWindow = window.open(url, '', 'height=500,width=700,menubar=no,resizable=yes,scrollbars=yes');
timerObj = window.setInterval("fun_To_ReTitle('~~newTitle~~ ')", 10);
}
function fun_To_ReTitle(newTitle){
if (newWindow.document.readyState == 'complete') {
newWindow.document.title=newTitle;
window.clearInterval(timerObj);
}
}

Categories

Resources