Document.writeln in a New frame not window.open - javascript

How can I write new lines on a frame in the same window? For now I have it creating a new Window with window.open. But now I need it in a frame.
I have an html with the two frames(form and result) and I need to write in the second by pressing a button on the first frame.
HTML
<html>
<head>
<title> Create Curriculum</title>
<meta charset="UTF-8"/>
</head>
<frameset rows="50%,50%">
<frame id="form" src="from.html"/>
<frame id="curri" src=""/>
</frameset>
You intercat with the form adding info to the inputs and saving the information. There's also a button that generates the curriculum using the info entered below.
JAVASCRIPT:
function genCurriculum() {
//I want to capture the second frame with id "curri"
var curri = parent.document.getElementById("curri");
curri.document.writeln("<h2>Head of the curriculum...</h2>");
//The others writeln for creating the curriculum
}
I want to know how to write in the frame, not in a new window.
And NOT using Jquery, just pure JavaScript. (Teacher requirement)

Is this jsfiddle what you want to have happen?
Html:
<form>
<input name="nextLine" type="text" />
<button type="button">
<span>Add a line</span>
</button>
</form>
<iframe height="100" width="200"></iframe>
JavaScript:
(function () {
'use strict';
var button, iframe, input;
function addLine (cD, input, val) {
return function () {
var body, line;
body = cD.getElementsByTagName('body')[0]
line = cD.createElement('p');
line.innerText = val.toString() + ': ' + input.value;
body.appendChild(line);
val += 1;
}
}
button = document.getElementsByTagName('button')[0];
iframe = document.getElementsByTagName('iframe')[0];
input = document.getElementsByTagName('input')[0];
button.addEventListener('click', addLine(iframe.contentDocument, input, 0), true);
}());

Related

function undefined when using iframe

I am making browser webapp in javascript. The strange problem is, whenever I add iframe tag in my html. The javascript stops working.
My html:
<input type="text" id="input">
<button onclick="sean()"></button>
<iframe id="outp" src="about:blank"></iframe>
My JS:
function sean(){
var input = document.getElementById('input').value;
var iframe = document.getElementById('outp')
iframe.src= "https://"+input
alert('worked');
};
The funny thing is as soon as I comment the iframe tag (not even modifying js) the function works and displays the alert message otherwise it keeps saying sean not defined.
Here is a pen showing error, if needed:
https://codepen.io/ShazamBolt8/pen/yLpqeXZ
If possible please add a working snippet.
Thanks in advance :)
let input = document.getElementById("txt");
let btn = document.getElementById("btn");
let iframe = document.getElementById("ifr");
btn.addEventListener("click", () => {
iframe.src = "https://" + input.value;
alert("wo4ked");
});
<input id="txt" type="text" >
<button id="btn">GO</button>
<iframe id="ifr" src="about:blank" frameborder="10"></iframe>

Can you write a Google Apps script that will recognize a Form submit and reveal a Site navigation button? [duplicate]

I am wondering if is possible to close the htmlservice popup when the submit button is hit on the Google form:
function launchForm() {
var form = FormApp.openById('15Qw9jmolybvMbx2d3UhddEWHrKe0zBiV5_asKXolsM0');
var formUrl = form.getPublishedUrl();
// var response = UrlFetchApp.fetch(formUrl);
// var formHtml = response.getContentText();
var htmlApp = HtmlService
.createHtmlOutput('<h1>Your Organization</h1>')
.append('<iframe src ="' + formUrl + '?embedded=true" width="1000" height="900" frameborder="0" marginheight="0" marginwidth="0">Loading...</iframe>')
.setTitle('Form')
.setWidth(1000)
.setHeight(1000);
SpreadsheetApp.getActiveSpreadsheet().show(htmlApp);
}
I'm hoping that when I hit the submit button on the form, the html app will close.
Google forms load each page on form navigation or submit. You can listen to those events, count the number of page loads and close the pop up.
Sample:
code.gs:
function showGoogleForm() {
var form = FormApp.openById(/*FORM EDIT ID*/);
var formUrl = form.getPublishedUrl();
var temp = HtmlService.createTemplateFromFile('googleForm');
temp.pubUrl = formUrl;
var htmlApp = temp
.evaluate()
.setTitle('Form')
.setWidth(1000)
.setHeight(1000);
SpreadsheetApp.getActiveSpreadsheet().show(htmlApp);
}
googleForm.html
<!DOCTYPE html>
<html lang="en">
<head>
<script type="text/javascript">
var i = 0;
var totalSections = 1; //TODO Set Total number of pages in your form
check = () => {
if (++i > totalSections) {
alert('Thank You for filling up the form');
setTimeout(google.script.host.close, 7);
}
};
</script>
</head>
<body>
<h1>
MASTER FORM
</h1>
<iframe
onload="check()"
referrerpolicy="no-referrer"
sandbox="allow-scripts allow-forms"
src="<?=pubUrl?>?embedded=true"
width="700"
height="520"
frameborder="0"
marginheight="0"
marginwidth="0"
></iframe>
</body>
</html>

Open popup in Javascript

I have a js rendered in HTML which would give a preview of the form. The code is functioning correctly but it gives me the output on the same page rather i want to open it in a pop-up window. I have tried using window.open () with no luck. Could you please help me out in how i can use window.open() for the below. The button ID is preview. When the button is clicked it executes a function similar to below
$("#preview").click(function() {
$("#formpreview").delete();
var fieldSet = ...................});
You can populate the html in the child window using the below example:
HTML
<!DOCTYPE Html />
<html>
<head>
<title></title>
</head>
<body>
<input type="button" id="launch" value="Launch Child Window"/>
<script type="text/javascript" src="theJS.js"></script>
</body>
</html>
JavaScript
var btnLaunch = document.getElementById("launch");
btnLaunch.onclick = function () {
var childWindow = window.open("", "", "height=500, width=500");
var html = "";
var theVariable = "Conent in Child Window";
html += "<p>" + theVariable + "</p>";
childWindow.document.body.innerHTML = html;
}
Store the popup as a variable, then set the popup's HTML to whatever you need.
$("#preview").click(function() {
var myWindow = window.open("", "Popup", "width=300, height=500");
myWindow.document.write("<html>This is where your content goes</html>");
});

Sending javascript variables into a frame

I'm trying to combine some dynamic parameters that are sent through the URL into a frame, but nothing works. Tried them inside the tags, outside, before, after... Can somebody shed a light on this?
URL on the top frame is http://www.someurl.com/someparameters.html?country=EN_US. The first script will get the language (EN) and market (US). Then, the frameset is built with another page and our target page, which should be called with the link "http://www.someurl.com/somefolders?LANGUAGE=EN&MARKET=US&somefixedparameters=123"
This is the source code of the frameset that isn't working.
<!DOCTYPE html>
<html>
<script type="text/javascript"><!--
var url = window.location.href;
var language = url.substr(url.indexOf("country=") + 8,2);
var market = url.substr(url.indexOf("country=") + 11,2);
}
</script>
<frameset rows="36px,*" frameborder="0">
<frame id="main" src="header_cgh.html?country=BR_OP" noresize="noresize" scrolling="no" border="1" bordercolor=white>
<frame id="flow" src="">
</frameset>
<script type="text/javascript"><!--
document.getElementById("flow").src = "http://www.someurl.com/somefolders?LANGUAGE=" + language + "&MARKET=" + market + "&somefixedparameters=123";
</script>
</html>
Thanks for your help!
UPDATE: After opening Chrome's Javascript console and inserting the command:
document.getElementById("flow").src = "http://www.someurl.com/somefolders?LANGUAGE=" + language + "&MARKET=" + market + "&somefixedparameters=123"
It returned the expected result. But it won't happen on its own.
Change your script to this:
window.onload = function() {
var url = window.location.href;
var language = url.substr(url.indexOf("country=") + 8,2);
var market = url.substr(url.indexOf("country=") + 11,2);
document.getElementById("flow").src = "/somefolders?language=" + language + "&market=" + market;
}
And put it in a script tag in your head.
Also, as a heads up: if someone requests the main frameset page without a query string, or without the country parameter in there, then indexOf returns -1, and you end up with nonsense in your language and market variables. You'll want to come up with a more robust way of getting that information.
Here is an example using postMessage. See if this handles what you're looking for:
<iframe src="http://a.JavaScript.info/files/tutorial/window/receive.html" id="iframe" style="height:60px"></iframe>
<form name="form">
<input type="text" name="msg" value="Your message"/>
<input type="submit"/>
</form>
<script>
var win = document.getElementById("iframe").contentWindow
document.forms.form.onsubmit = function() {
win.postMessage(
this.elements.msg.value,
"http://a.JavaScript.info"
)
return false
}
</script>
From http://javascript.info/tutorial/cross-window-messaging-with-postmessage

IE losing iframe contents after back/forward key

This problem is only happening in IE (at least 8 and 9). After an element is dynamically added to the DOM, the contents of an embedded iframe are lost when the page is reentered with a BACK/FORWARD key. Just two small HTML files will reproduce the issue.
The first file is iframe.htm:
<!DOCTYPE html>
<html>
<head>
<title>IE iframe bug</title>
<script type="text/javascript">
function mytrace(msg) {
var t = document.createTextNode(msg);
var b = document.createElement('br');
var d = document.getElementById("trace_output")
d.appendChild(t);
d.appendChild(b); /// will work if commented
}
function submitListing() {
mytrace('submitListing()');
var doc = document.getElementById("output_iframe")
.contentWindow.document;
var d = new Date;
doc.location.replace('report.htm?invalidateCache=' + d.getTime());
//mytrace('submitListing(): out');
}
</script>
</head>
<body>
<div id="trace_output"><br /></div>
<input type="button" onclick="submitListing();" value="Run" /><br />
<iframe id="output_iframe" src=""></iframe>
</body>
</html>
The second file is report.htm:
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
LINK
</body>
</html>
Steps to recreate the issue (BACK KEY)
Place above content in two files
Browse the iframe.htm file
Press the Run button to load report.htm in the iframe
Click on the LINK link to load a different page
Press the browser BACK button to returned to the "cached" (lmao) page
iframe contents are gone!!!! (only in IE-- safari, chrome, firefox retain the contents)
Also..(FORWARD KEY)
Browse to an arbitrary page (for history, http://www.google.com works)
Load iframe.htm into the same tab
Press the Run button to load report.htm in the iframe
Press the browser BACK button to return to the first page
Press the browser FORWARD button to return to iframe.htm
iframe contents are gone again!!
Now comment out the line:
d.appendChild(b)
That one change allows everything to work in IE. However, my solution needs to make those kinds of DOM manipulations (heavy jQuery/AJAX app) AND be able to restore the iframe across browser BACK/FORWARD actions.
It seems that I will have to remember the contents of the iframe so that I can restore it when the page is accessed with the BACK/FORWARD keys. I'm not thrilled with this because sometimes the iframe content will be quite large and it could chew up a bit of memory and time to make another copy of the embedded document for the restore. I would love to hear some other ideas about how I could approach this. Thanks in advance.
EDIT
The following replacement to iframe.htm will work around the problem with IE. I'm going to rewrite this using jQuery and add some more logic to restore the scroll positions. I had hoped for something more elegant, but this is doing the job.
<!DOCTYPE html>
<html>
<head>
<title>IE iframe bug</title>
<script type="text/javascript">
function myTrace(msg) {
var t = document.createTextNode(msg);
var b = document.createElement('br');
var d = document.getElementById("trace_output")
d.appendChild(t);
d.appendChild(b);
}
var make_backup ="false";
function submitListing() {
make_backup = "true";
myTrace('submitListing()');
var doc = document.getElementById("output_iframe").contentWindow.document;
var d = new Date;
doc.location.replace('report.htm?invalidateCache=' + d.getTime());
//myTrace('submitListing(): out');
}
function iframe_load() {
myTrace("iframe loaded, is_cached=" + document.getElementById("is_cached").value);
if (make_backup == "true") { // only when submitting
var htm, doc;
make_backup = "false"
doc = document.getElementById("output_iframe").contentWindow.document;
htm = doc.documentElement.innerHTML;
document.getElementById("iframe_backup").value = htmlEscape(htm);
}
}
function bodyLoaded() {
var is_cached = document.getElementById("is_cached");
if (is_cached.value == "false") { // initial page load
is_cached.value = "true";
}
else { // BACK or FORWARD, restore DOM where needed
var htm;
htm = htmlUnescape(document.getElementById("iframe_backup").value);
var doc;
doc = document.getElementById("output_iframe").contentWindow.document;
doc.open();
doc.writeln(htm);
doc.close();
}
}
function htmlEscape(str) {
return String(str).replace(/&/g, '&').replace(/"/g, '"')
.replace(/'/g, ''').replace(/</g, '<').replace(/>/g, '>');
}
function htmlUnescape(str) {
return String(str).replace(/&/g,'&').replace(/"/g,'"')
.replace(/'/g,"'").replace(/</g,'<').replace(/>/g,'>');
}
</script>
</head>
<body onload="bodyLoaded();">
<div id="trace_output" style="height: 300px; border-width:1; background-color: Silver"><br></div>
<input id="is_cached" type="hidden" value="false">
<input id="iframe_backup" type="hidden">
<input type="button" onclick="submitListing();" value="Run"><br>
<iframe id="output_iframe" src="" onload="iframe_load();"></iframe>
</body>
</html>
EDIT 2
Rewritten with jQuery:
<!DOCTYPE html>
<html>
<head>
<title>IE iframe workaround2</title>
<script type="text/javascript" src="Scripts/jquery-1.7.1.js"></script>
<script type="text/javascript">
var make_backup = "false";
$(document).ready(function () {
myTrace('document ready()');
var is_cached = $("#is_cached");
if (is_cached.val() == "false") { // initial page load
is_cached.val("true");
}
else { // BACK or FORWARD, restore DOM where needed
if ($.browser.msie) { // IE loses iframe content; restore
var htm = htmlUnescape($("#iframe_backup").val());
var doc = $("#output_iframe")[0].contentWindow.document;
doc.open();
doc.writeln(htm);
doc.close();
myTrace('iframe contents restored');
}
}
$('#output_iframe').load(function () {
myTrace("iframe_loaded");
if (make_backup == "true") { // only when submitting
make_backup = "false"
if ($.browser.msie) {
var doc = $("#output_iframe")[0].contentWindow.document;
var htm = doc.documentElement.innerHTML;
$("#iframe_backup").val(htmlEscape(htm));
myTrace('iframe contents backed up');
}
}
});
$('#submit_listing').click(function () {
make_backup = "true";
myTrace('submitListing()');
var doc = $("#output_iframe")[0].contentWindow.document;
var d = new Date;
doc.location.replace('report.htm?invalidateCache='+d.getTime());
});
});
function myTrace(msg) {
$('#trace_output').append(msg + '<br>');
}
function htmlEscape(str) {
return String(str).replace(/&/g, '&').replace(/"/g, '"')
.replace(/'/g, ''').replace(/</g, '<').replace(/>/g, '>');
}
function htmlUnescape(str) {
return String(str).replace(/&/g,'&').replace(/"/g,'"')
.replace(/'/g,"'").replace(/</g,'<').replace(/>/g,'>');
}
</script>
</head>
<body>
<div id="trace_output"
style="height: 300px; border-width:1; background-color: Silver">
<br></div>
<div style="display: block;">
<input id="is_cached" type="text" value="false">
<input id="iframe_backup" type="text" type="hidden"></div>
<input id="submit_listing" type="button" value="Run"><br>
<iframe id="output_iframe" src=""></iframe>
</body>
</html>

Categories