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.
I have an HTML document with an iFrame, which i am loading in a webbrowser window. My objective is once that iFrame document is loaded, capture the document contents and search for a particular line.
I am not been able to do it so far, any suggestions ?
HTML CODE
<html>
<body>
<iframe id="monitor" src="http://monitor.baseline.com"></iframe>
</body>
</html>
You can add a JavaScript function to the OnLoad event of the iFrame:
document.getElementById('monitor').onload = function() { }
And then follow these solutions to parse your document. But be aware about cross-site-scripting restrictions. If the src of your iFrame is a totally different domain, it probably won't work.
i got it by doing the below
var javascript = #"
var Frame = document.getElementById('monitor');
window.external.iFrameCheck(Frame.contentWindow.document);
";
var doc = (IHTMLDocument2)webBrowser1.Document;
//Once we have the document, execute our JavaScript in it
doc.parentWindow.execScript(javascript);
this would then call the below c# code
[PermissionSet(SecurityAction.Demand, Name = "FullTrust")]
[ComVisible(true)]
public class ComVisibleObjectForScripting
{
public void iFrameCheck(HTMLDocument FrameDoc)
{
//Do what you want here with your FrameDoc
// the innerHTML will give you the content of the iframe
}
}
I'm attempting to open 1-6 potential valid popups (in reality it's a foreach item in a valid collection) via a registered startup script like this:
While (int i < 6)
{
ScriptManager.RegisterStartupScript(this.Page, typeof(System.Web.UI.Page), "OpenWin", "<script type='text/javascript'>openNewWin ('" + url + "')</script>", false);
i++;
}
The markup is as follows:
<head>
<script language="javascript" type="text/javascript">
function openNewWin(url)
{
var x = window.open(url, 'mynewwin', 'width=620,height=250,toolbar=1');
x.focus();
}
</script>
</head>
But I'm only seeing one window open, when i step through, the code seems to execute successfully, what gives?
In your window.open call, you are using the same name (mynewwin). Thus each subsequent call to open results in the URL being loaded into the first window with that name. You could use _blank and it would open each in a new window:
var x = window.open(url, '_blank', 'width=620,height=250,toolbar=1');
That being said, I agree that it's difficult to imagine this not being a poor user experience.
I have an IFrame embedding a youtube video. I want to create a textbox where user (admins) can paste a new src (URL) of video and the IFrame take the new source. Here is what I have so far:
protected void Edited_Click(object sender, EventArgs e)
{
// HtmlControl frame1 = (HtmlControl)this.FindControl("frame1");
string url = TextBox1.Text;
frame1.Attributes["src"] = url;
}
And in the html code is the Iframe:
<div id="video">
<iframe title="YouTube video player" runat="server" width="420"
frameborder="1" style="height: 265px; float: left;
text-align: center;" id="frame1"
name="frame1" align="middle"></iframe>
<br />
</div>
I don't set any src in the beginning but when I paste a URL in the textbox and hit the button, the Iframe doesn't displays anything.
Other responses don't answer the question, they provide an alternative. The question is how to set iFrame src from C#. I'll answer that here.
I'm all for "right tools for the job" and use that mantra a lot myself - but only when the other tools are "wrong". That hasn't been established here. Can someone provide a good technical reason why this should not be done in code-behind?
I think the issue #Pepys is experiencing might be due to something in the URL, which he hasn't provided yet. For example, maybe his URL includes ampersands or other characters which need to be escaped.
The following code works fine for me:
excelframe.Attributes["src"] =
#"https://r.office.microsoft.com/r/rlidExcelEmbed?"
+ #"su=-0000000000"
+ #"&Fi=zzzzzzzzzzzz!111"
+ #"&ak=x%3d9%26x%3d9%26x%3d!zzzzzzzzzz"
+ #"&kip=1"
+ #"&AllowTyping=True"
+ #"&ActiveCell='sheet1'!C3"
+ #"&wdHideGridlines=True"
+ #"&wdHideHeaders=True"
+ #"&wdDownloadButton=True";
You need to do this on the client browser, not server-side. I would suggest something like:
// (Add inside script element in head of page html)
window.onload = function() {
document.getElementById('<id of input>').onchange = function() {
changeFrameUrl();
}
};
function changeFrameUrl() {
var inputVal = document.getElementById('<id of input>').value;
document.getElementById('<id of iframe>').src = inputVal;
}
Hope this helps - it's off the top of my head though, so don't diss me if it doesn't work first time!
This isn't working:
Response.Write(" DELETE ");
<script language="javascript" type="text/javascript">
function Delete(path) {
path1 = unescape(path);
var myObject = new ActiveXObject("Scripting.FileSystemObject");
var myFolder = myObject.GetFolder(path1);
myFolder.Delete();
alert("Welcome");
}
</script>
But this worked.
Response.Write(" DELETE ");
<script language="javascript" type="text/javascript">
function Delete() {
alert("Welcome");
}
</script>
I tried with onclick for Delete() to get just ALERT it worked well.
But it isn't working when add the parameters.Can you help me please.Trying for this from long time please.
First of all, \u is escpae code for a hex digit. So better re-format it.
Second, href=view.aspx?type=notes is not a valid html syntax too. Double quotes please.
Third, please put some code to check if your javascript variables (myObject,myFolder) are valid (not null) before invoke any method against them.