window.document in IE - javascript

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?

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.

Quill.js add a custom javascript function into the editor

I am using Quill.js to have users create custom user designed pages off the main web page. I have a custom slider that I have written in javascript that will take images and rotate through them. I have the toolbar in quill setup to be able to click on the toolbar to setup the slider in a modal window.
When the user clicks to close the modal slider setup window, I'm trying to insert an edit button in the html editor where the cursor sits so the user can edit the information that was just entered or possible delete the button by removing all the information in the slider modal window.
I have written custom blots, followed all the examples I could find and nothing worked. I did get a custom html tag to show, but not a button. When I requested the html from quill when I setup the custom html tag in the editor, all I get is "" from quill.root.innerHTML none of the custom tag or the information in it even though I see it correctly in the editor.
I would like a button in the editor to make it easy to edit the slider data, as there could be more than one. I am not going to limit the number of sliders. It is up to the user to ruin their own page.
I will not be rendering the slider in the edit html window, just trying to display a button to click on. I do give the user a preview button on the modal window to view the slider if they so choose.
I also would like to store the setup information of the slider in a data tag in json format in the button and change that html button to a tag along with the json data when rendering the html in the browser window.
Can this be done in Quill.js?
I did this by using the import blots embed. I don't register as a button but clicking on the blot I do get a link to the embedded data and trigger the edit of the carousel data on that click.
var Quill;
const BlockEmbed = Quill.import("blots/block/embed");
const Link = Quill.import('formats/link');
class Carousel extends BlockEmbed {
static create(value) {
var self = this;
const node = super.create(value);
node.dataset.carousel = JSON.stringify(value);
value.file.frames.forEach(frame => {
const frameDiv = document.createElement("div");
frameDiv.innerText = frame.title;
frameDiv.className += "previewDiv";
node.appendChild(frameDiv);
});
node.onclick = function () {
if (Carousel.onClick) {
Carousel.onClick(self, node);
}
};
return node;
}
static value(domNode) {
return JSON.parse(domNode.dataset.carousel);
}
static onClick: any;
static blotName = "carousel";
static className = "ql-carousel";
static tagName = "DIV";
}
Quill.register("formats/carousel", Carousel);
I then include this as a script on the page where quill is editing the HTML
<script src="~/js/quilljs-carousel.js"></script>
And then this is the custom javascript to handle the events of the blot displayed in a custom modal dialog in a hidden div tag
<script>
function CarouselClicked(blot, node) {
editCarousel(JSON.parse(node.dataset.carousel), node);
}
var Carousel = Quill.import("formats/carousel");
Carousel.onClick = CarouselClicked;
function carouselToolbarClickHandler() {
createCarousel();
}
var Toolbar = Quill.import("modules/toolbar");
Toolbar.DEFAULTS.handlers.carousel = carouselToolbarClickHandler;
$(document).ready(function() {
var div = $("#editor-container");
var Image = Quill.import('formats/image');
Image.className = "img-fluid";
Quill.register(Image, true);
var quill = new Quill(div.get(0),
{
modules: {
syntax: true,
toolbar: '#toolbar-container'
},
theme: 'snow'
});
div.data('quill', quill);
// Only show the toolbar when quill is ready to go
$('#toolbar-container').css('display', 'block');
div.css('display', 'block');
$('#editor-loading').css('display', 'none');
// Override the quill Image handler and create our own.
quill.getModule("toolbar").addHandler("image", imageHandler);
});
function createCarousel() {
$("#carouselModalForm").removeClass("was-validated").get(0).reset();
$("#carouselModalList").empty();
$("#carouselModal")
.data("state", "unsaved")
.one("hidden.bs.modal",
function() {
var data = getCarouselData();
var carouselData = {};
carouselData['file'] = data;
carouselData['speed'] = $('#time').val();
carouselData['height'] = $('#height').val();
carouselData['width'] = $('#width').val();
var quill = $("#editor-container").data().quill;
var range = quill.getSelection(true);
if (range != null) {
quill.insertEmbed(
range.index,
"carousel",
carouselData,
Quill.sources.USER
);
quill.setSelection(range.index + 2, Quill.sources.USER);
}
})
.modal("show");
$('#title').get(0).outerText = "Create Carousel";
}
function editCarousel(value, node) {
$("#carouselModalForm").get(0).reset();
var elem = $("#carouselModalList").empty();
$.each(value.file.frames,
function(i, data) {
$("<option>").appendTo(elem).text(data.title).data("frame", data);
});
$('#time').val(value.speed);
$('#height').val(value.height);
$('#width').val(value.width);
var modal = $("#carouselModal");
modal.find("form").removeClass("was-validated");
modal
.data("state", "unsaved")
.one("hidden.bs.modal",
function() {
if ($("#carouselModal").data("state") !== "saved")
return;
var data = getCarouselData();
var carouselData = {};
carouselData['file'] = data;
carouselData['speed'] = $('#time').val();
carouselData['height'] = $('#height').val();
carouselData['width'] = $('#width').val();
var carousel = Quill.find(node, true);
carousel.replaceWith("carousel", carouselData);
})
.modal("show");
$('#title').get(0).outerText = "Edit Carousel";
}
function getCarouselData() {
var options = $("#carouselModalList").find("option");
var frames = $.map(options,
function(domNode) {
return $(domNode).data("frame");
});
return {
frames : frames
};
}
function getCarouselFrameFormData() {
// Get data from frame
function objectifyForm(formArray) { //serialize data function
var returnArray = {};
for (var i = 0; i < formArray.length; i++) {
returnArray[formArray[i]['name']] = formArray[i]['value'];
}
return returnArray;
}
return objectifyForm($("#carouselFrameModalForm").serializeArray());
}
$("#carouselModalNewFrame").click(function() {
$("#carouselFrameModalForm").removeClass("was-validated").get(0).reset();
$("#backgroundPreview").attr("src", "");
$("#mainPreview").attr("src", "");
$("#carouselFrameModal")
.data("state", "unsaved")
.one("hidden.bs.modal",
function() {
if ($("#carouselFrameModal").data("state") == "saved") {
var data = getCarouselFrameFormData();
$("<option>").appendTo($("#carouselModalList")).text(data.title).data("frame", data);
}
})
.modal("show");
// Fetch all the forms we want to apply custom Bootstrap validation styles to
});
$("#carouselModalEditFrame").click(function () {
var form = $("#carouselFrameModalForm");
form.removeClass("was-validated").get(0).reset();
var selected = $("#carouselModalList option:selected");
var frame = selected.data("frame");
$.each(Object.keys(frame),
function (i, e) {
$("input[name=" + e + "]", form).val(frame[e]);
});
$("#backgroundPreview").attr("src", frame.backgroundImg);
$("#mainPreview").attr("src", frame.mainImg);
$("#carouselFrameModal")
.data("state", "unsaved")
.one("hidden.bs.modal",
function() {
if ($("#carouselFrameModal").data("state") == "saved") {
var data = getCarouselFrameFormData();
selected.text(data.title).data("frame", data);
}
})
.modal("show");
});
$("#carouselModalRemoveFrame").click(function () {
$("#confirm-delete").modal("show");
});
$("#carouselFrameModalForm").find("input:file").change(function() {
var elem = $(this);
var target = elem.data("target");
var preview = elem.data("preview");
FiletoBase64(this, preview, target);
});
$("#carouselModalList").change(function() {
var selected = $("option:selected", this);
$("#carouselModalEditFrame,#carouselModalRemoveFrame").prop("disabled", !selected.length);
});
$("#carouselModalSave").click(function() {
// Validate frameset
var form = $("#carouselModalForm").get(0);
var select = $("#carouselModalList");
if (select.find("option").length == 0) {
select.get(0).setCustomValidity("Need at least one frame");
} else {
select.get(0).setCustomValidity("");
}
if (form.checkValidity()) {
$("#carouselModal").data("state", "saved");
$("#carouselModal").modal("hide");
}
else {
$("#carouselModalForm").addClass("was-validated");
}
});
$("#carouselFrameModalSave").click(function() {
// Validate frame
if ($("#carouselFrameModalForm").get(0).checkValidity()) {
$("#carouselFrameModal").data("state", "saved");
$("#carouselFrameModal").modal("hide");
}
else {
$("#carouselFrameModalForm").addClass("was-validated");
}
});
$('#confirm-delete-delete').click(function () {
$("#carouselModalList option:selected").remove();
$("#confirm-delete").modal("hide");
});
// #region Image FileExplorer Handler
function insertImageToEditor(url) {
var div = $("#editor-container");
var quill = div.data('quill');
var range = quill.getSelection();
quill.insertEmbed(range.index, 'image', url);
}
function CarouselMainimageHandler() {
$("#CarouselMainimageSelectFileExplorer").fileExplorer({
directoryListUrl: '#Url.Action("DirectoryList", "FileTree")',
fileListUrl: '#Url.Action("FileList", "FileTree")'
});
$("#CarouselMainimageSelectModal").modal("show");
}
$("#CarouselMainimageSelectModal").on("hide.bs.modal",
function() {
$("#CarouselMainimageSelectFileExplorer").fileExplorer("destroy");
});
$("#CarouselMainimageSelectSelectButton").click(function() {
var id = $("#CarouselMainimageSelectFileExplorer").fileExplorer("getSelectedFileId");
if (id == null) {
alert("Please select a file");
return;
}
var imageName = $("#CarouselMainimageSelectFileExplorer").fileExplorer("getSelectedFileName");
var imageLink = "#Url.Action("Render", "FileTree")?id=" + id;
$("#mainImageName").val(imageName);
$("#mainImageLink").val(imageLink);
$("#mainImage").attr("src",imageLink);
$("#mainImage").show();
$("#CarouselMainimageSelectModal").modal("hide");
});
function CarouselBackgroundimageHandler() {
$("#CarouselBackgroundimageSelectFileExplorer").fileExplorer({
directoryListUrl: '#Url.Action("DirectoryList", "FileTree")',
fileListUrl: '#Url.Action("FileList", "FileTree")'
});
$("#CarouselBackgroundimageSelectModal").modal("show");
}
$("#CarouselBackgroundimageSelectModal").on("hide.bs.modal",
function() {
$("#CarouselBackgroundimageSelectFileExplorer").fileExplorer("destroy");
});
$("#CarouselBackgroundimageSelectSelectButton").click(function() {
var id = $("#CarouselBackgroundimageSelectFileExplorer").fileExplorer("getSelectedFileId");
if (id == null) {
alert("Please select a file");
return;
}
var imageName = $("#CarouselBackgroundimageSelectFileExplorer").fileExplorer("getSelectedFileName");
var imageLink = "#Url.Action("Render", "FileTree")?id=" + id;
$("#backgroundImageName").val(imageName);
$("#backgroundImageLink").val(imageLink);
$("#backgroundImage").attr("src",imageLink);
$("#backgroundImage").show();
$("#CarouselBackgroundimageSelectModal").modal("hide");
});
function imageHandler() {
$("#imageSelectFileExplorer").fileExplorer({
directoryListUrl: '#Url.Action("DirectoryList", "FileTree")',
fileListUrl: '#Url.Action("FileList", "FileTree")'
});
$("#imageSelectModal").modal("show");
}
$("#imageSelectModal").on("hide.bs.modal",
function() {
$("#imageSelectFileExplorer").fileExplorer("destroy");
});
$("#imageSelectSelectButton").click(function() {
var id = $("#imageSelectFileExplorer").fileExplorer("getSelectedFileId");
if (id == null) {
alert("Please select a file");
return;
}
insertImageToEditor("#Url.Action("Render", "FileTree")?id=" + id);
$("#imageSelectModal").modal("hide");
});
// #endregion
function Save() {
var div = $("#editor-container");
var quill = div.data('quill');
$('#alertSave').show();
$.post({
url: '#Url.Action("Save")',
data: { BodyHtml: quill.root.innerHTML, locationId: #(Model.LocationId?.ToString() ?? "null") },
headers: {
'#Xsrf.HeaderName': '#Xsrf.RequestToken'
}
}).done(function() {
$('#alertSave').hide();
$('#alertSuccess').show();
setTimeout(function() { $('#alertSuccess').hide(); }, 5000);
}).fail(function(jqXhr, error) {
var alert = $('#alertFailure');
var text = $("#alertFailureText");
text.text(error.ErrorMessage);
alert.show();
});
}
function FiletoBase64(input, imgName, Base64TextName) {
var preview = document.getElementById(imgName);
var file = input.files[0];
var reader = new FileReader();
reader.addEventListener("load",
function() {
preview.src = reader.result;
document.getElementById(Base64TextName).value = reader.result;
},
false);
if (file) {
reader.readAsDataURL(file);
}
}
</script>

Browser Full screen feature

Hi I have the below page where you simply click the button Full screen and the page browser takes up the full screen, the navigation controls are also hidden to - which is what I like. However if you page refresh (or in my case my page refreshes every 5 minutes) the navigation controls return and it is no longer the view as previous. How can I solve this so that when it refreshed the navigation etc doesn't return and it remains full screen?
<html>
<head>
</head>
<body>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.5.0/css/font-awesome.min.css" />
<script src="screenfull.js"></script>
<script>
$(function () {
$('#supported').text('Supported/allowed: ' + !!screenfull.enabled);
if (!screenfull.enabled) {
return false;
}
$('#request').click(function () {
screenfull.request($('#container')[0]);
// does not require jQuery, can be used like this too:
// screenfull.request(document.getElementById('container'));
});
$('#exit').click(function () {
screenfull.exit();
});
function fullscreenchange() {
var elem = screenfull.element;
$('#status').text('Is fullscreen: ' + screenfull.isFullscreen);
if (elem) {
$('#element').text('Element: ' + elem.localName + (elem.id ? '#' + elem.id : ''));
}
if (!screenfull.isFullscreen) {
$('#external-iframe').remove();
document.body.style.overflow = 'hidden';
}
}
document.addEventListener(screenfull.raw.fullscreenchange, fullscreenchange);
// set the initial values
fullscreenchange();
});
</script>
<button id="request"><i class="fa fa-arrows-alt"></i> Request</button>
<button id="exit">Exit</button>
</body>
(function () {
'use strict';
var isCommonjs = typeof module !== 'undefined' && module.exports;
var keyboardAllowed = typeof Element !== 'undefined' && 'ALLOW_KEYBOARD_INPUT' in Element;
var fn = (function () {
var val;
var valLength;
var fnMap = [
[
'requestFullscreen',
'exitFullscreen',
'fullscreenElement',
'fullscreenEnabled',
'fullscreenchange',
'fullscreenerror'
],
// new WebKit
[
'webkitRequestFullscreen',
'webkitExitFullscreen',
'webkitFullscreenElement',
'webkitFullscreenEnabled',
'webkitfullscreenchange',
'webkitfullscreenerror'
],
// old WebKit (Safari 5.1)
[
'webkitRequestFullScreen',
'webkitCancelFullScreen',
'webkitCurrentFullScreenElement',
'webkitCancelFullScreen',
'webkitfullscreenchange',
'webkitfullscreenerror'
],
[
'mozRequestFullScreen',
'mozCancelFullScreen',
'mozFullScreenElement',
'mozFullScreenEnabled',
'mozfullscreenchange',
'mozfullscreenerror'
],
[
'msRequestFullscreen',
'msExitFullscreen',
'msFullscreenElement',
'msFullscreenEnabled',
'MSFullscreenChange',
'MSFullscreenError'
]
];
var i = 0;
var l = fnMap.length;
var ret = {};
for (; i < l; i++) {
val = fnMap[i];
if (val && val[1] in document) {
for (i = 0, valLength = val.length; i < valLength; i++) {
ret[fnMap[0][i]] = val[i];
}
return ret;
}
}
return false;
})();
var screenfull = {
request: function (elem) {
var request = fn.requestFullscreen;
elem = elem || document.documentElement;
// Work around Safari 5.1 bug: reports support for
// keyboard in fullscreen even though it doesn't.
// Browser sniffing, since the alternative with
// setTimeout is even worse.
if (/5\.1[\.\d]* Safari/.test(navigator.userAgent)) {
elem[request]();
} else {
elem[request](keyboardAllowed && Element.ALLOW_KEYBOARD_INPUT);
}
},
exit: function () {
document[fn.exitFullscreen]();
},
toggle: function (elem) {
if (this.isFullscreen) {
this.exit();
} else {
this.request(elem);
}
},
raw: fn
};
if (!fn) {
if (isCommonjs) {
module.exports = false;
} else {
window.screenfull = false;
}
return;
}
Object.defineProperties(screenfull, {
isFullscreen: {
get: function () {
return Boolean(document[fn.fullscreenElement]);
}
},
element: {
enumerable: true,
get: function () {
return document[fn.fullscreenElement];
}
},
enabled: {
enumerable: true,
get: function () {
// Coerce to boolean in case of old WebKit
return Boolean(document[fn.fullscreenEnabled]);
}
}
});
if (isCommonjs) {
module.exports = screenfull;
} else {
window.screenfull = screenfull;
}
})();
Online Demo : https://plnkr.co/edit/zx0rXwXpJbWdMvh3HQ25?p=preview
Make onepage website (ajax) (no refresh) Use history pushstate to save all your links so you can use history navigation and change your URL. (most of time I use this approach.)
Or you can use localstorage to save state.
Theoretically You can store an indication of what was the previews state (full-screen / normal) in the browser storage.
Then on page load, read the stored value and activate full-screen if necessary.
However, modern browsers require this to be an interactive user action (not automatically via script on load)
If you try to automate this, you'll get these type of warnings in the browser's console:
Alternatives
Avoid full refreshes
Workaround using custom browser extension to restore the fullscreen state

Navigating to Blacklisted URL's and Canceling Them

I need to write a Firefox extension that creates a blacklist and whitelist of URL's, and checks to make sure the user wants to navigate to them whenever the user attempts to do so. I'm doing this using a main script and a content script that I attach to every page (using PageMod); I attached a listener using jQuery to every link (with the tag "a") which executes a function using window.onbeforeunload. I have two questions:
How would I prompt/ask the user if they actually did want to go to the site?
How would I stop the browser from navigating to the site if the user decided not to?
Right now my code passes messages between the two scripts in order to accomplish my goal; as far as I can tell, I can only use "document" in the content script, and save the blacklist/whitelist in the main script. I'm using simple-storage to save my lists, and the port module to pass messages between the scripts.
For question 1, I've attempted using confirm(message) to get a positive/negative response from the user, but the popup either doesn't show up or shows up for a split second then gets automatically answered with a negative response. When I look in my console's error messages, I see a "prompt aborted by user" error.
For question 2, I've already tried using event.preventDefault() by passing the click event to the function (this worked, I think). Is there a better way to do this? I've seen people using window.location = "", et cetera to do this.
Anyways, the code is below:
MAIN.JS
var ss = require("sdk/simple-storage");
exports.main = function() {
if (!ss.storage.blacklist) {
ss.storage.blacklist = [];}
if (!ss.storage.whitelist) {
ss.storage.whitelist = [];}
var data = require("sdk/self").data;
var pageMod = require("sdk/page-mod");
pageMod.PageMod({
include: "*",
contentScriptFile: [data.url("jquery-1.10.2.min.js"),data.url("secChk.js")],
onAttach: function(worker) {
function whiteCNTD(str) {
for (var index = 0; index < ss.storage.whitelist.length; index++) {
if (ss.storage.whitelist[index] == str) {
return index;
}
}
return -1;
}
function blackCNTD(str) {
for (var index = 0; index < ss.storage.blacklist.length; index++) {
if (ss.storage.blacklist[index] == str) {
return index;
}
}
return -1;
}
function checkLists(URL) {
if (whiteCNTD(URL) == -1) {
if (blackCNTD(URL) != -1) {
var bool = false;
worker.port.emit("navq", "Do you want to go to this link and add it to the whitelist?");
worker.port.on("yes", function() {
bool = true;
});
worker.port.on("no", function() {
bool = false;
});
if (bool == true) {
ss.storage.blacklist.splice(index, 1);
ss.storage.whitelist.push(URL);
return true;
}
else {
return false;
}
}
else {
var bool = false;
worker.port.emit("safeq", "Is this a safe site?");
worker.port.on("yes", function() {
bool = true;
});
worker.port.on("no", function() {
bool = false;
});
if (bool == true) {
ss.storage.whitelist.push(URL);
return true;
}
else {
ss.storage.blacklist.push(URL);
return false;
}
}
}
return true;
}
worker.port.on("newURL", function(URL) {
var s = "";
s = URL;
if (checkLists(s)) {
worker.port.emit("good", s);
} else if (!checkLists(s)) {
worker.port.emit("bad", s);
}
});
}
});
}
SECCHK.JS
//Check if the site is a bad site whenever a link is clicked
$("a").click(function(event) {
window.onbeforeunload = function() {
self.port.on("navq", function(message) {
var r = confirm("Do you want to go to this link and add it to the whitelist?");
if (r == true) {
self.port.emit("yes", message);
} else if (r == false) {
self.port.emit("no", message);
}
});
self.port.on("safeq", function(message) {
var r = confirm("Is this a safe site?");
if (r == true) {
self.port.emit("yes", temp);
} else if (r == false) {
self.port.emit("no", temp);
}
});
link = document.activeElement.href;
self.port.emit("newURL", link);
self.port.on("good", function(message) {
return true;
});
self.port.on("bad", function(message) {
return false;
});
}
});

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