Set title in the window popup - javascript

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

Related

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.

How to close current tab using javascript in chrome without using window.close()?

I want to create a Webpage which is used to conduct online examination so if user switches to other tabs, the examination must be ended after 1st view and current tab must be closed.
I already used page visibility API in Javascript to find the number of views user switches to other tabs.window.close() is not working in chrome.
if(document.hidden==true){
views++;
if(views==1){
close_window();return false();
}
alert( "Your view count is: <b>" + views +
". " + "Your page current state is: " +
document[(prefix === "" ? "v" : prefix + "V") + "isibilityState"] + "</b><br />");
}
}
function testPageVisibilityApi() {
if (prefix === null)
document.getElementById("log").innerHTML = "Your browser does not support Page Visibility API";
else {
document.addEventListener(prefix + "visibilitychange", countView);
countView();
}
}
Any suggestions?
To close the particular tab, you can implement function like:
(function() {
'use strict';
$("#close_page").click(function() {
var confirm_result = confirm("Are you sure you want to quit?");
if (confirm_result == true) {
window.close();
}
});
})();
var Activetab;
window.onfocus = function () {
Activetab = true;
};
window.onblur = function () {
Activetab = false;
};
// check periodically
setInterval(function () {
console.log(window.Activetab ? 'active' : 'inactive');
}, 2000);
this may help you to detect when the user changes tabs, this is working fine and referred from here
UPDATED
var Activetab;
window.onfocus = function () {
Activetab = true;
};
window.onblur = function () {
Activetab = false;
// window.close();
open("yourpathoffile/filename.ext", '_self').close(); // or you can
try directly window.close
};
// check periodically
setInterval(function () {
console.log(window.Activetab ? 'active' : 'inactive');
}, 2000);
JS:
function close_window() {
if (confirm("Close Window?")) {
close();
}
}
HTML:
close
or:
close
We added return false here to prevent the default behavior for the event. Otherwise the browser will attempt to go to that URL.
Refer to this article for Firefox.

How do I close a showModalDialog() generated via a polyfill from another function?

I have used the following showModalDialog polyfill for my code. It seems to be working fine except I cannot close it without pressing the close button on the iframe.
(function() {window.showModalDialog = window.showModalDialog || function(url, arg, opt) {
url = url || ''; //URL of a dialog
arg = arg || null; //arguments to a dialog
opt = opt/* || 'dialogWidth:300px;dialogHeight:200px'*/; //options: dialogTop;dialogLeft;dialogWidth;dialogHeight or CSS styles
var caller = showModalDialog.caller.toString();
var dialog = document.body.appendChild(document.createElement('dialog'));
dialog.setAttribute('style', opt.replace(/dialog/gi, ''));
dialog.setAttribute('id', 'dialogID');
dialog.innerHTML = '×<iframe id="dialog-body" src="' + url + '" style="border: 0; width: 100%; height: 100%;"></iframe>';
document.getElementById('dialog-body').contentWindow.dialogArguments = arg;
document.getElementById('dialog-close').addEventListener('click', function(e) {
e.preventDefault();
dialog.close();
});
dialog.showModal();
document.getElementById('dialog-body').addEventListener('click', function(e) {
e.preventDefault();
dialog.close();
});
dialog.addEventListener('close', function() {
var returnValue = document.getElementById('dialog-body').contentWindow.returnValue;
document.body.removeChild(dialog);
nextStmts[0] = nextStmts[0].replace(/(window\.)?showModalDialog\(.*\)/g, JSON.stringify(returnValue));
eval('{\n' + nextStmts.join('\n'));
});
throw 'Execution stopped until showModalDialog is closed';
};
})();`
I need to close the generated dialogbox on the press of a yes or no button from the passed URL. The url is of a web page that has a yes and a no button and calls this function onClick.
function dialogButtonClick(dialogFlag)
{
if(dialogFlag=='YES')
{
window.returnValue = 'YES';
}
window.close();
}
Window.close() does not seem to work. I am unable to return the click value from the dialogbox to the parent code. Could anyone help me find a solution for this?
Try this:
dialogButtonClick = (dialogFlag) => {
if (dialogFlag == 'YES') { open(location, '_self').close(); }
return false;
}

Closing a JavaScript window with an onclick event

We have to make a JavaScript that opens a new Window, and then you need to be able to close it again with a click inside the window.
But my code does not work, could someone please provide me an answer to how this is done best?
function swipe() {
var largeImage = document.getElementById('largeImage');
var url = largeImage.getAttribute('src');
var w = largeImage.naturalWidth;
var h = largeImage.naturalHeight;
window.open(url,"Image", "height="+ h +", width="+ w +", resizable=yes");
var myWindow = window.self;
myWindow.addEventListener("click", clickHandler);
var elementIsClicked = false;
function clickHandler(){
elementIsClicked = true
}
function isElementClicked (){
if(elementIsClicked){
newWindow.close();
}
}
setInterval(isElementClicked, 500);
}
A comment says that newWindow is not defined anywhere. I think you meant to use the myWindow object. myWindow.close() will work, since it closes the window.
If you want to execute this when this first loads, you should put this in a window.onload function or a self-invoking function. Also, for full compatibility within all browsers, you should omit the resizable=yes part, because that is supported in only IE.
Also, if you want to use jQuery, you can execute this method within an $(window).load() function.
You can utilize document.write()
window.onload = function() {
var largeImage = document.getElementById("largeImage");
// var url = largeImage.getAttribute('src');
var w = largeImage.naturalWidth;
var h = largeImage.naturalHeight;
// open blank `window`
var popup = window.open("", "Image"
, "height="+ h
+", width="+ w
+", resizable=yes");
// write `img` `outerHTML` to `popup` `window`
popup.document.write(largeImage.outerHTML);
window.onclick = function() {
// close `popup`
popup.document.write("<script>this.close()<\/script>");
// remove `onclick` handler
this.onclick = null;
}
}
plnkr http://plnkr.co/edit/0KUPw3UlEF0ONO1vDoOU?p=preview
var newWindow;
function windowOpener() {
var url = "http://stackoverflow.com/questions/36387144/closing-a-javascript-window-with-an-onclick-event";
newWindow = window.open(url, "Popup", "width=700,height=500");
var timer = setInterval(function() {
if (newWindow.closed) {
alert("window closed");
clearInterval(timer);
}
}, 250)
}
<button onclick="windowOpener();">Open a window</button>
Here is the code for opening and detecting whenever it closes.
Here is the sample code on codepen.io http://codepen.io/sujeetkrjaiswal/pen/vGebqy
The code is not runnig in the stackoverflow for some reason, try it on codepen.
Thank you all for your answers.
Here is the solution to my problem:
function swipe() {
var largeImage = document.getElementById('largeImage');
var url = largeImage.getAttribute('src');
var w = largeImage.naturalWidth;
var h = largeImage.naturalHeight;
var popup = window.open(url,"Image", "height="+ h +", width="+ w +", resizable=yes");
popup.document.write('<img src="women_running_small.jpg" id="largeImage" style="width:95% ;height:95%; object-fit:contain"/>');
popup.onclick = function() {
// close `popup`
popup.document.write("<script>this.close()<\/script>");
// remove `onclick` handler
this.onclick = null;
}
}

Display data on different browser tabs

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

Categories

Resources