I'm using Safari 6.0.5.
I open a new empty window, try to change the title to 'debug window', nothing happens. With a check function checking every 10 milliseconds, it says the window.document.title is 'Debug Window', still the new Window title bar says it is 'untitled'.
var debug_window = window.open('', 'debug_window', 'height=200');
debug_window.document.title = 'Debug Window';
function check()
{
debugLog(1, 'title:' + debug_window.document.title);
if(debug_window.document) { // if loaded
debug_window.document.title = "debug_window"; // set title
} else { // if not loaded yet
setTimeout(check, 10); // check in another 10ms
}
}
check();
The output in the debugLog is:
17:35:04.558: title:
17:35:04.584: title:debug_window
What is going wrong here that the new window is still called 'untitled'?
Thanks!
Now the second argument to window.open() is a frame/window-name and serves also as the default title. This is eventually overridden by the document loaded into this window. Opening the document-stream and inserting a basic html-document should serve the purpose:
var debug_window = window.open('', 'debug_window', 'height=200');
debug_window.document.open();
debug_window.document.write('<!DOCTYPE html>\n<html lang="en">\n<head>\n<title>Debug Window</title>\n</head>\n<body></body>\n</html>');
debug_window.document.close();
var debug_body = debug_window.document.getElementsByTagName('body')[0];
// write to debug_window
debug_body.innerHTML = '<p>Message</p>';
So you would be setting up a basic document inside the window, just as it would be loaded by the server (by writing to the "document stream"). Then you would start to manipulate this document like any other.
Edit: Does not work in Safari either.
Other suggestion: set up a basic document (including the title) on the server and inject the content into its body on load. As a bonus, you may setup CSS via stylesheets.
var debug_window = window.open('debug_template.html', 'debug_window', 'height=200');
debug_window.onload = function() {
var debug_body = debug_window.document.getElementsByTagName('body')[0];
debug_body.innerHTML = '...';
// or
// var el = document.createElement('p');
// p.innerHTML = '...';
// debug_body.appendChild(p);
debug_window.onload=null; // clean up cross-reference
};
And on the server side something like
<!DOCTYPE html>
<html lang="en">
<head>
<title>Debug Window</title>
<link rel="stylesheet" href="debug_styles.css" type="text/css" />
</head>
<body></body>
</html>
If this still should not work (e.g.: writing to the debug-window's document is without effect), you could call your app from inside the debug-window by something like:
<body onload="if (window.opener && !window.opener.closed) window.opener.debugCallback(window, window.document);">
</body>
(So you would check if the opener – your App – exists and hasn't been closed in the meantime and then call a callback-function "debugCallback()" in your app with the debug-window and its document as arguments.)
Try:
var debug_window = window.open('about:blank', 'debug_window', 'height=200');
Related
I want to click an element (button) several times in a remote website loaded through webview in Electron.
The following works when I enter it in the console (via inspect element):
a = setInterval( function(){
var elem = document.getElementsByClassName("myclass");
elem[0].click()
},1000)
It doesn't when I use it in Electron main script:
window.webContents.executeJavaScript('a = setInterval( function(){ var elem = document.getElementsByClassName("myclass"); elem[0].click() },1000)', true);
I get an error:
Uncaught TypeError: Cannot read property 'click' of undefined at :1:110
I also tried the scipt preloaded in webview tag, but no luck.
What am I missing, or doing wrong?
chromiumVersion: "58.0.3029.110"
electronVersion: "1.7.9"
nodeVersion:"7.9.0"
EDIT
Testing with Google.com and the speech icon in the searchbar:
var element = document.getElementsByClassName('gsst_a');
if (typeof(element) != 'undefined' && element != null) {
console.log('yep, element is found');
console.log(element);
console.log(element[0]);
a = setInterval(
function(){
var elem = document.getElementsByClassName("gsst_a");
elem[0].click()
},1000)
} else {
console.log('nope, element is not found');
}
This clicks the icon every 1 second in Chrome when entered in console.
When I have my webview set to Google.com and have the following line, it still finds the element, but gives the error mentioned earlier again:
window.webContents.executeJavaScript('var element=document.getElementsByClassName("gsst_a");void 0!==element&&null!=element?(console.log("yep, element is found"),console.log(element),console.log(element[0]),a=setInterval(function(){document.getElementsByClassName("gsst_a")[0].click()},1e3)):console.log("nope, element is not found");', true);
console.log(element) gives: HTMLCollection(0)
console.log(element[0]) gives: undefined
Why can I enter the js in my normal browser, but not in Electron webview?
To answer my own question.
The event's referring to the web page in the BrowserWindow, not the webview within that. So the element doesn't exist in the scope I was looking in, and I needed to do something similar within the BrowserWindow.
Code:
<html>
<head>
<style type="text/css">
* { margin: 0; }
#browserGoogle { height: 100%; }
</style>
</head>
<body>
<webview id="browserGoogle" src="https://google.com"></webview>
<script>
const browserView = document.getElementById('browserGoogle')
browserView.addEventListener('dom-ready', () => {
const browser = browserView.getWebContents()
browser.setDevToolsWebContents(devtoolsView.getWebContents())
browser.webContents.executeJavaScript('var element=document.getElementsByClassName("gsst_a");void 0!==element&&null!=element?(console.log("yep, element is found"),console.log(element),console.log(element[0]),a=setInterval(function(){document.getElementsByClassName("gsst_a")[0].click()},1e3)):console.log("nope, element is not found");', true);
})
</script>
</body>
</html>
I have a web application. It runs in Google Chrome and is not required to work in any other browser.
I have PDF data which has been generated on the server and sent back to the client in an AJAX request.
I create a blob from the PDF data.
I use window.URL.createObjectURL to create a URL from the blob, which I then load into a window (my preview_window) which has previously been created to show the PDF.
To load the URL, I set preview_window.location.href.
I would like to call revokeObjectURL to avoid wasting more and more resources as new PDFs are generated and previewed in the window.
The problem is that calling it immediately after setting preview_window.location.href is too soon, and stops the PDF from being displayed. So I would like to call revokeObjectURL only once the URL has been loaded.
I have tried setting preview_window.onload to a callback for this purpose, but it never gets called.
I would like to know:
Is it possible to trigger a callback when the window has loaded the URL, as I am trying to do? How?
Is there another approach to ensure revokeObjectURL gets called in a timely manner?
If I cannot trigger revokeObjectURL when the window finishes loading the URL, I may revoke each URL immediately before generating a new one. But I would rather revoke the URL as soon as it is done loading, if possible.
I have prepared a html file which demonstrates the situation pretty well:
<html>
<head>
<title>Show PDF Demo</title>
<script>
var build_blob = function(mime_type, data) {
var buf = new ArrayBuffer(data.length);
var ia = new Uint8Array(buf);
for (var i = 0; i < data.length; i++) ia[i] = data.charCodeAt(i);
var blob = new Blob([ buf ], { type: mime_type });
return blob;
};
window.onload = function(e) {
document.getElementById('preview_button').onclick = function(e) {
// open the window in the onclick handler so we don't trigger popup blocking
var preview_window = window.open(null, 'preview_window');
// use setTimeout to simulate an asynchronous AJAX request
setTimeout(function(e) {
var pdf_data = atob(
"JVBERi0xLjQKMSAwIG9iago8PCAvVHlwZSAvQ2F0YWxvZwovT3V0bGluZXMgMiAwIFIKL1BhZ2Vz" +
"IDMgMCBSCj4+CmVuZG9iagoyIDAgb2JqCjw8IC9UeXBlIC9PdXRsaW5lcwovQ291bnQgMAo+Pgpl" +
"bmRvYmoKMyAwIG9iago8PCAvVHlwZSAvUGFnZXMKL0tpZHMgWzQgMCBSXQovQ291bnQgMQo+Pgpl" +
"bmRvYmoKNCAwIG9iago8PCAvVHlwZSAvUGFnZQovUGFyZW50IDMgMCBSCi9NZWRpYUJveCBbMCAw" +
"IDUwMCAyMDBdCi9Db250ZW50cyA1IDAgUgovUmVzb3VyY2VzIDw8IC9Qcm9jU2V0IDYgMCBSCi9G" +
"b250IDw8IC9GMSA3IDAgUiA+Pgo+Pgo+PgplbmRvYmoKNSAwIG9iago8PCAvTGVuZ3RoIDczID4+" +
"CnN0cmVhbQpCVAovRjEgMjQgVGYKMTAwIDEwMCBUZAooU01BTEwgVEVTVCBQREYgRklMRSkgVGoK" +
"RVQKZW5kc3RyZWFtCmVuZG9iago2IDAgb2JqClsvUERGIC9UZXh0XQplbmRvYmoKNyAwIG9iago8" +
"PCAvVHlwZSAvRm9udAovU3VidHlwZSAvVHlwZTEKL05hbWUgL0YxCi9CYXNlRm9udCAvSGVsdmV0" +
"aWNhCi9FbmNvZGluZyAvTWFjUm9tYW5FbmNvZGluZwo+PgplbmRvYmoKeHJlZgowIDgKMDAwMDAw" +
"MDAwMCA2NTUzNSBmCjAwMDAwMDAwMDkgMDAwMDAgbgowMDAwMDAwMDc0IDAwMDAwIG4KMDAwMDAw" +
"MDEyMCAwMDAwMCBuCjAwMDAwMDAxNzkgMDAwMDAgbgowMDAwMDAwMzY0IDAwMDAwIG4KMDAwMDAw" +
"MDQ2NiAwMDAwMCBuCjAwMDAwMDA0OTYgMDAwMDAgbgp0cmFpbGVyCjw8IC9TaXplIDgKL1Jvb3Qg" +
"MSAwIFIKPj4Kc3RhcnR4cmVmCjYyNQolJUVPRg=="
);
/*
Warning: for my Chrome (Version 44.0.2403.155 m), the in-built PDF viewer doesn't seem
to work with a blob when this html page is loaded from the local filesystem. I have only
got this to work when fetching this page via HTTP.
*/
var pdf_blob = build_blob('application/pdf', pdf_data);
var pdf_url = window.URL.createObjectURL(pdf_blob);
preview_window.onload = function(e) {
console.log("preview_window.onload called"); // never happens
window.URL.revokeObjectURL(pdf_url);
};
preview_window.location.href = pdf_url;
console.log("preview_window.location.href set");
}, 500);
};
};
</script>
</head>
<body>
<button id="preview_button">Show Preview</button>
</body>
</html>
Although my demo code above avoids it, I do have jQuery loaded for my application, so if that makes things easier I'm open to using it.
I did find this question in a search, but in that situation the main window ("window") is pointed to a new URL, and the OP never got a response when asking in comments whether it makes a difference if the window came from window.open.
As you found out, you can't set open()ed windows' onload event from the opener.
You will have to inject some script in the second page that will call its window.opener functions.
But since you are opening a pdf file, the browser will re-parse entirely your page and your injected code will vanish.
The solution, as you found out yourself in the comments, is to inject the blob's url in an iframe, and wait for this iframe's load event.
Here is how :
index.html
<script>
// The callback that our pop-up will call when loaded
function imDone(url){
window.URL.revokeObjectURL(url);
}
var build_blob = function(mime_type, data) {
var buf = new ArrayBuffer(data.length);
var ia = new Uint8Array(buf);
for (var i = 0; i < data.length; i++) ia[i] = data.charCodeAt(i);
var blob = new Blob([ buf ], { type: mime_type });
return blob;
};
var preview_window=null;
window.onload = function(e) {
document.getElementById('preview_button').onclick = function(e) {
if(preview_window===null || preview_window.closed){
// open the window in the onclick handler so we don't trigger popup blocking
preview_window = window.open('html2.html', 'preview_window');
}
// avoid reopening the window since it may cache our last blob
else preview_window.focus();
// use setTimeout to simulate an asynchronous AJAX request
setTimeout(function(e) {
var pdf_data = /* Your pdf data */
var pdf_blob = build_blob('application/pdf', pdf_data);
var pdf_url = window.URL.createObjectURL(pdf_blob);
// Simple loop if our target document is not ready yet
var loopLoad = function(url){
var doc = preview_window.document;
if(doc){
var iframe = doc.querySelector('iframe');
if(iframe)iframe.src = url;
else setTimeout(function(){loopLoad(url);},200);
}
else setTimeout(function(){loopLoad(url);},200)
};
loopLoad(pdf_url);
}, 0);
};
};
</script>
and the html2.html
<html>
<head>
<title>Iframe PDF Demo</title>
<style>
body, html, iframe{margin:0; border:0}
</style>
</head>
<body>
<iframe width="100%" height="100%"></iframe>
<script>
document.querySelector('iframe').onload = function(){
//first check that our src is set
if(this.src.indexOf('blob')===0)
// then call index.html's callback
window.opener.imDone(this.src);
}
</script>
</body>
</html>
Live Demo
I'm a newbie with JavaScript and I asked a question earlier and got answers which helped me, but I thought I could incorporate it into the larger form I was working with and now I'm stuck again.
I have a large form with one select option. When the form is filled out, a new window opens and incorporates the values submitted into an invitation type page.
Everything else is working except for this select option. The problem I am having is depending on the selection, I want different text to be written into the new window (as part of the overall new window invitation page).
I'm really close, mostly b/c of help I received earlier today -- I can either get the new window to show just my named option value or I can get a whole new window with the different text (that is not part of the invitation page). I just can't combine the two.
I wrote up a smaller page in case someone wants to take a look at it. Thanks in advance.
<!doctype html>
<html>
<head>
<title>JavaScript Forms</title>
<meta charset="utf-8">
<link rel="stylesheet" type="text/css" href="mystyle.css">
<script type="text/JavaScript">
function newWindow() {
allInfo = open("", "displayWindow");
allInfo.document.open();
allInfo.document.write('<!doctype html><html><head><link rel="stylesheet" type="text/css" href="mystyle_invite.css"><title>Resume</title><meta charset="utf-8"> </head><body>');
allInfo.document.write(document.getElementById ('firstname').value);
allInfo.document.write('</body></html>');
allInfo.document.close();
}
function showName() {
var doIt=document.getElementById('firstname').value;
if ( doIt == "Michael" ) {
allInfo.document.write("Mr. " + doIt); //only "Mikey" is written out
}
else if ( doIt == "Sam" ) {
allInfo.document.write("Mrs. " + doIt);
}
else {
allInfo.document.write("Sir " + doIt);
}
}
</script>
</head>
<body>
<script type="text/JavaScript">
</script>
<form id="infoForm" method="post" name="infoForm">
<p>First Name:</p>
<p><select id="firstname" onChange="showName()" >
<option value="Mikey">nickname1</option>
<option value="Sammy">nickname2</option>
<option value="Sir Doug">nickname3</option>
</select></p>
<p> <input type="button" value="Submit Information" onClick="newWindow()"></p>
</form>
</body>
</html>
There are somethings that can help a lot here. First opening a second window can be a painful experience both for the user and the programmer. Unless you have an absolute need I would recommend manipulating the current window's DOM to display a popup instead.
Next if you can use DOM methods to change the page contents. document.write comes with a lot of problems which in your case are not apparent. Mainly it can erase you current DOM. You don't notice this in your example because the new window is blank so rewriting it is incidental.
Finally your use of allInfo is a quirky way to reference a global variable. It is not easily understood that this is happening from the style of code. In fact any linter will throw an error for your use of the global and will case an error if you declare "use strict" in your functions. Best to learn the good coding practises way.
Since we will want to interact with a variable (allInfo) in your case we should encapsulate the value in an object. This object can hold the state of that reference and offer some abstracted interactions with it. By doing so you avoid polluting the global name space and allow you to swap out your implementation without having to rewrite the parts of your program that depend on it.
// Our welcome window object
function WelcomeWindow() {
// save a reference to the content of your new window
// to be printed when ready. (Lazy execution)
this.innerHTML = '';
}
WelcomeWindow.prototype.open = function() {
this.win = window.open("", "displayWindow");
return this;
};
WelcomeWindow.prototype.close = function() {
this.win.close();
return this;
};
WelcomeWindow.prototype.write = function(html) {
this.innerHTML += '' + html;
return this;
};
WelcomeWindow.prototype.render = function() {
if (!this.win) { throw new Error("window has not been opened yet."); }
this.win.open();
this.win.write('<!doctype html><html><head><link rel="stylesheet" type="text/css" href="mystyle_invite.css"><title>Resume</title><meta charset="utf-8"> </head><body>');
this.win.write(this.innerHTML);
this.win.write('</body></html>');
this.win.close();
return this;
};
This allows us to declaratively manipulate the window before it is opened. For example if we want to add the name to the window:
function NameField(id) {
this.element = document.getElementById(id);
}
NameField.prototype.toString = function() {
var name = this.element.value;
switch (name) {
case 'Michael': return 'Mr. Michael';
case 'Sam': return 'Mrs. Sam';
default: return 'Sir ' + name;
}
};
NameField.prototype.toHtml = function() {
return '<strong>' + this.toString() + '</strong>';
};
Linking it together using code instead because adding events into the DOM only confuses the separation of markup and code.
window.onload = function() {
var form = document.getElementById('infoForm');
form.onsubmit = function(e) {
e.preventDefault();
var name = new NameField('firstName');
new WelcomWindow()
.write(name.toHtml())
.open()
.render();
return false;
};
};
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())
How would I open a new window in JavaScript and insert HTML data instead of just linking to an HTML file?
I would not recomend you to use document.write as others suggest, because if you will open such window twice your HTML will be duplicated 2 times (or more).
Use innerHTML instead
var win = window.open("", "Title", "toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=yes,resizable=yes,width=780,height=200,top="+(screen.height-400)+",left="+(screen.width-840));
win.document.body.innerHTML = "HTML";
You can use window.open to open a new window/tab(according to browser setting) in javascript.
By using document.write you can write HTML content to the opened window.
When you create a new window using open, it returns a reference to the new window, you can use that reference to write to the newly opened window via its document object.
Here is an example:
var newWin = open('url','windowName','height=300,width=300');
newWin.document.write('html to write...');
Here's how to do it with an HTML Blob, so that you have control over the entire HTML document:
https://codepen.io/trusktr/pen/mdeQbKG?editors=0010
This is the code, but StackOverflow blocks the window from being opened (see the codepen example instead):
const winHtml = `<!DOCTYPE html>
<html>
<head>
<title>Window with Blob</title>
</head>
<body>
<h1>Hello from the new window!</h1>
</body>
</html>`;
const winUrl = URL.createObjectURL(
new Blob([winHtml], { type: "text/html" })
);
const win = window.open(
winUrl,
"win",
`width=800,height=400,screenX=200,screenY=200`
);
You can open a new popup window by following code:
var myWindow = window.open("", "newWindow", "width=500,height=700");
//window.open('url','name','specs');
Afterwards, you can add HTML using both myWindow.document.write(); or myWindow.document.body.innerHTML = "HTML";
What I will recommend is that first you create a new html file with any name.
In this example I am using
newFile.html
And make sure to add all content in that file such as bootstrap cdn or jquery, means all the links and scripts. Then make a div with some id or use your body and give that a id. in this example I have given id="mainBody" to my newFile.html <body> tag
<body id="mainBody">
Then open this file using
<script>
var myWindow = window.open("newFile.html", "newWindow", "width=500,height=700");
</script>
And add whatever you want to add in your body tag. using following code
<script>
var myWindow = window.open("newFile.html","newWindow","width=500,height=700");
myWindow.onload = function(){
let content = "<button class='btn btn-primary' onclick='window.print();'>Confirm</button>";
myWindow.document.getElementById('mainBody').innerHTML = content;
}
myWindow.window.close();
</script>
it is as simple as that.
You can also create an "example.html" page which has your desired html and give that page's url as parameter to window.open
var url = '/example.html';
var myWindow = window.open(url, "", "width=800,height=600");
Use this one. It worked for me very perfect.
For New window:
new_window = window.open(URL.createObjectURL(new Blob([HTML_CONTENT], { type: "text/html" })))
for pop-up
new_window = window.open(URL.createObjectURL(new Blob([HTML_CONTENT], { type: "text/html" })),"width=800,height=600")
Replace HTML_CONTENT with your own HTML Code
Like:
new_window = window.open(URL.createObjectURL(new Blob(["<h1>Hello</h1>"], { type: "text/html" })))
if your window.open() & innerHTML works fine, ignore this answer.
following answer only focus on cross-origin access exception
#key-in_short,workaround:: [for cross-origin access exception]
when you exec code in main.html -- which tries to access file window_ImageGallery.html by using window.open() & innerHTML
for anyone who encounter cross-origin access exception
and you dont want to disable/mess_around_with Chrome security policy
-> you may use query string to transfer the html code data, as a workaround.
#details::
#problem-given_situation,#problem-arise_problem::
say you exec following simple window.open command as other answer suggested.
let window_Test = window.open('window_ImageGallery.html', 'Image Enlarged Window' + $(this).attr('src'), 'width=1000,height=800,top=50,left=50');
window_Test.document.body.innerHTML = 'aaaaaa';
you may encounter following cross-origin access exception
window_Test.document.body.innerHTML = 'aaaaaa'; // < Exception here
Uncaught DOMException: Blocked a frame with origin "null" from accessing a cross-origin frame.
=> #problem-solution-workaround::
you may use query string to transfer the html code data, as a workaround. <- Transfer data from one HTML file to another
#eg::
in your main.html
// #>> open ViewerJs in a new html window
eleJq_Img.click(function() {
// #>>> send some query string data -- a list of <img> tags, to the new html window
// #repeat: must use Query String to pass html code data, else you get `Uncaught DOMException: Blocked a frame with origin "null" from accessing a cross-origin frame.` (cross origin access issue)
let id_ThisImg = this.id;
let ind_ThisImg = this.getAttribute('data-index-img');
let url_file_html_window_ImageGallery = 'window_ImageGallery.html'
+ '?queryStr_html_ListOfImages=' + encodeURIComponent(html_ListOfImages)
+ '&queryStr_id_ThisImg=' + encodeURIComponent(id_ThisImg)
+ '&queryStr_ind_ThisImg=' + encodeURIComponent(ind_ThisImg);
// #>>> open ViewerJs in a new html window
let window_ImageGallery = window.open(url_file_html_window_ImageGallery, undefined, 'width=1000,height=800,top=50,left=50');
});
in your window_ImageGallery.html
window.onload = function () {
// #>> get parameter from URL
// #repeat: must use Query String to pass html code data, else you get `Uncaught DOMException: Blocked a frame with origin "null" from accessing a cross-origin frame.` (cross origin access issue)
// https://stackoverflow.com/questions/17502071/transfer-data-from-one-html-file-to-another
let data = getParamFromUrl();
let html_ListOfImages = decodeURIComponent(data.queryStr_html_ListOfImages);
let id_ThisImgThatOpenedTheHtmlWindow = decodeURIComponent(data.queryStr_id_ThisImg);
let ind_ThisImgThatOpenedTheHtmlWindow = decodeURIComponent(data.queryStr_ind_ThisImg);
// #>> add the Images to the list
document.getElementById('windowImageGallery_ContainerOfInsertedImages').innerHTML = html_ListOfImages;
// -------- do your stuff with the html code data
};
function getParamFromUrl() {
let url = document.location.href;
let params = url.split('?')[1].split('&');
let data = {};
let tmp;
for (let i = 0, l = params.length; i < l; i++) {
tmp = params[i].split('=');
data[tmp[0]] = tmp[1];
}
return data
}
#minor-note::
(seems) sometimes you may not get the cross-origin access exception
due to, if you modify the html of 'window_ImageGallery.html' in main.html before window_ImageGallery.html is loaded
above statement is based on my test
& another answer -- window.open: is it possible open a new window with modify its DOM
if you want to make sure to see that Exception,
you can try to wait until the opening html window finish loading, then continue execute your code
#eg::
use defer() <- Waiting for child window loading to complete
let window_ImageGallery = window.open('window_ImageGallery.html', undefined, 'width=1000,height=800,top=50,left=50');
window_ImageGallery.addEventListener("unload", function () {
defer(function (){
console.log(window_ImageGallery.document.body); // < Exception here
});
});
function defer (callback) {
var channel = new MessageChannel();
channel.port1.onmessage = function (e) {
callback();
};
channel.port2.postMessage(null);
}
or use sleep() with async What is the JavaScript version of sleep()?
eleJq_Img.click(async function() {
...
let window_Test = window.open( ...
...
await new Promise(r => setTimeout(r, 2000));
console.log(window_Test.document.body.innerHTML); // < Exception here
});
or you get null pointer exception
if you try to access elements in window_ImageGallery.html
#minor-comment::
There are too many similar Posts about the cross-origin issue. And there are some posts about window.open()
Idk which post is the best place to place the answer. And I picked here.