iframe onload with src not working in IE11 - javascript

I have a JavaScript program that gets the last modified date of a txt file. The code works fine in Firefox but for some reason, it does nothing in IE11. My code is listed below.
JavaScript code:
function getLastMod(){
var myFrm = document.getElementById('myIframe');
var lastMod = new Date(myFrm.contentWindow.document.lastModified);
var getSpan = document.getElementById('LastModified');
getSpan.innerHTML += "<font color=red> (File Last Updated: " + lastMod.toLocaleString() + ")</font>";
}
HTML code:
<span id="LastModified"></span>
<iframe id="myIframe" onload="getLastMod()" src="date.txt" style="display:none;"></iframe>

I had a similar issue when I tried to define the event in the tag. I had better results assigning the event from within javascript.
<script type="text/javascript">
document.getElementById('myIframe').onload = function() {
getLastMod();
}
</script>

Related

How to render HTML file using JavaScript [duplicate]

I want home.html to load in <div id="content">.
<div id="topBar"> HOME </div>
<div id ="content"> </div>
<script>
function load_home(){
document.getElementById("content").innerHTML='<object type="type/html" data="home.html" ></object>';
}
</script>
This works fine when I use Firefox. When I use Google Chrome, it asks for plug-in. How do I get it working in Google Chrome?
I finally found the answer to my problem. The solution is
function load_home() {
document.getElementById("content").innerHTML='<object type="text/html" data="home.html" ></object>';
}
Fetch API
function load_home (e) {
(e || window.event).preventDefault();
fetch("http://www.yoursite.com/home.html" /*, options */)
.then((response) => response.text())
.then((html) => {
document.getElementById("content").innerHTML = html;
})
.catch((error) => {
console.warn(error);
});
}
XHR API
function load_home (e) {
(e || window.event).preventDefault();
var con = document.getElementById('content')
, xhr = new XMLHttpRequest();
xhr.onreadystatechange = function (e) {
if (xhr.readyState == 4 && xhr.status == 200) {
con.innerHTML = xhr.responseText;
}
}
xhr.open("GET", "http://www.yoursite.com/home.html", true);
xhr.setRequestHeader('Content-type', 'text/html');
xhr.send();
}
based on your constraints you should use ajax and make sure that your javascript is loaded before the markup that calls the load_home() function
Reference - davidwalsh
MDN - Using Fetch
JSFIDDLE demo
You can use the jQuery load function:
<div id="topBar">
HOME
</div>
<div id ="content">
</div>
<script>
$(document).ready( function() {
$("#load_home").on("click", function() {
$("#content").load("content.html");
});
});
</script>
Sorry. Edited for the on click instead of on load.
Fetching HTML the modern Javascript way
This approach makes use of modern Javascript features like async/await and the fetch API. It downloads HTML as text and then feeds it to the innerHTML of your container element.
/**
* #param {String} url - address for the HTML to fetch
* #return {String} the resulting HTML string fragment
*/
async function fetchHtmlAsText(url) {
return await (await fetch(url)).text();
}
// this is your `load_home() function`
async function loadHome() {
const contentDiv = document.getElementById("content");
contentDiv.innerHTML = await fetchHtmlAsText("home.html");
}
The await (await fetch(url)).text() may seem a bit tricky, but it's easy to explain. It has two asynchronous steps and you could rewrite that function like this:
async function fetchHtmlAsText(url) {
const response = await fetch(url);
return await response.text();
}
See the fetch API documentation for more details.
I saw this and thought it looked quite nice so I ran some tests on it.
It may seem like a clean approach, but in terms of performance it is lagging by 50% compared by the time it took to load a page with jQuery load function or using the vanilla javascript approach of XMLHttpRequest which were roughly similar to each other.
I imagine this is because under the hood it gets the page in the exact same fashion but it also has to deal with constructing a whole new HTMLElement object as well.
In summary I suggest using jQuery. The syntax is about as easy to use as it can be and it has a nicely structured call back for you to use. It is also relatively fast. The vanilla approach may be faster by an unnoticeable few milliseconds, but the syntax is confusing. I would only use this in an environment where I didn't have access to jQuery.
Here is the code I used to test - it is fairly rudimentary but the times came back very consistent across multiple tries so I would say precise to around +- 5ms in each case. Tests were run in Chrome from my own home server:
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-2.1.4.min.js"></script>
</head>
<body>
<div id="content"></div>
<script>
/**
* Test harness to find out the best method for dynamically loading a
* html page into your app.
*/
var test_times = {};
var test_page = 'testpage.htm';
var content_div = document.getElementById('content');
// TEST 1 = use jQuery to load in testpage.htm and time it.
/*
function test_()
{
var start = new Date().getTime();
$(content_div).load(test_page, function() {
alert(new Date().getTime() - start);
});
}
// 1044
*/
// TEST 2 = use <object> to load in testpage.htm and time it.
/*
function test_()
{
start = new Date().getTime();
content_div.innerHTML = '<object type="text/html" data="' + test_page +
'" onload="alert(new Date().getTime() - start)"></object>'
}
//1579
*/
// TEST 3 = use httpObject to load in testpage.htm and time it.
function test_()
{
var xmlHttp = new XMLHttpRequest();
xmlHttp.onreadystatechange = function() {
if (xmlHttp.readyState == 4 && xmlHttp.status == 200)
{
content_div.innerHTML = xmlHttp.responseText;
alert(new Date().getTime() - start);
}
};
start = new Date().getTime();
xmlHttp.open("GET", test_page, true); // true for asynchronous
xmlHttp.send(null);
// 1039
}
// Main - run tests
test_();
</script>
</body>
</html>
try
async function load_home(){
content.innerHTML = await (await fetch('home.html')).text();
}
async function load_home() {
let url = 'https://kamil-kielczewski.github.io/fractals/mandelbulb.html'
content.innerHTML = await (await fetch(url)).text();
}
<div id="topBar"> HOME </div>
<div id="content"> </div>
When using
$("#content").load("content.html");
Then remember that you can not "debug" in chrome locally, because XMLHttpRequest cannot load -- This does NOT mean that it does not work, it just means that you need to test your code on same domain aka. your server
You can use the jQuery :
$("#topBar").on("click",function(){
$("#content").load("content.html");
});
$("button").click(function() {
$("#target_div").load("requesting_page_url.html");
});
or
document.getElementById("target_div").innerHTML='<object type="text/html" data="requesting_page_url.html"></object>';
<script>
var insertHtml = function (selector, argHtml) {
$(document).ready(function(){
$(selector).load(argHtml);
});
var targetElem = document.querySelector(selector);
targetElem.innerHTML = html;
};
var sliderHtml="snippets/slider.html";//url of slider html
var items="snippets/menuItems.html";
insertHtml("#main",sliderHtml);
insertHtml("#main2",items);
</script>
this one worked for me when I tried to add a snippet of HTML to my main.html.
Please don't forget to add ajax in your code
pass class or id as a selector and the link to the HTML snippet as argHtml
There is this plugin on github that load content into an element. Here is the repo
https://github.com/abdi0987/ViaJS
load html form a remote page ( where we have CORS access )
parse the result-html for a specific portion of the page
insert that part of the page in a div on current-page
//load page via jquery-ajax
$.ajax({
url: "https://stackoverflow.com/questions/17636528/how-do-i-load-an-html-page-in-a-div-using-javascript",
context: document.body
}).done(function(data) {
//the previous request fails beceaus we dont have CORS on this url.... just for illlustration...
//get a list of DOM-Nodes
var dom_nodes = $($.parseHTML(data));
//find the question-header
var content = dom_nodes.find('#question-header');
//create a new div and set the question-header as it's content
var newEl = document.createElement("div");
$(newEl).html(content.html());
//on our page, insert it in div with id 'inserthere'
$("[id$='inserthere']").append(newEl);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p>part-result from other page:</p>
<div id="inserthere"></div>
Use this simple code
<div w3-include-HTML="content.html"></div>
<script>w3.includeHTML();</script>
</body>```
This is usually needed when you want to include header.php or whatever page.
In Javascript it's easy especially if you have HTML page and don't want to use php include function but at all you should write php function and add it as Javascript function in script tag.
In this case you should write it without function followed by name Just. Script rage the function word and start the include header.php
i.e convert the php include function to Javascript function in script tag and place all your content in that included file.
I use jquery, I found it easier
$(function() {
$("#navigation").load("navbar.html");
});
in a separate file and then load javascript file on html page
showhide.html
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
function showHide(switchTextDiv, showHideDiv)
{
var std = document.getElementById(switchTextDiv);
var shd = document.getElementById(showHideDiv);
if (shd.style.display == "block")
{
shd.style.display = "none";
std.innerHTML = "<span style=\"display: block; background-color: yellow\">Show</span>";
}
else
{
if (shd.innerHTML.length <= 0)
{
shd.innerHTML = "<object width=\"100%\" height=\"100%\" type=\"text/html\" data=\"showhide_embedded.html\"></object>";
}
shd.style.display = "block";
std.innerHTML = "<span style=\"display: block; background-color: yellow\">Hide</span>";
}
}
</script>
</head>
<body>
<a id="switchTextDiv1" href="javascript:showHide('switchTextDiv1', 'showHideDiv1')">
<span style="display: block; background-color: yellow">Show</span>
</a>
<div id="showHideDiv1" style="display: none; width: 100%; height: 300px"></div>
</body>
</html>
showhide_embedded.html
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
function load()
{
var ts = document.getElementById("theString");
ts.scrollIntoView(true);
}
</script>
</head>
<body onload="load()">
<pre>
some text 1
some text 2
some text 3
some text 4
some text 5
<span id="theString" style="background-color: yellow">some text 6 highlight</span>
some text 7
some text 8
some text 9
</pre>
</body>
</html>
If your html file resides locally then go for iframe instead of the tag. tags do not work cross-browser, and are mostly used for Flash
For ex : <iframe src="home.html" width="100" height="100"/>

Change the inner HTML with another HTML code block of a div and a script

I have been struggling with this so hopefully someone can help!
So I am looking to change the inner html of a paragraph to another html element containing a div and script when my frame receives a message from the page code. I have this working only for when the inner html is set to replace with a normal string
like this
document.getElementById('demo').innerHTML = "testing" ;
the correct replacement shows up here
<p id="demo">testing</p>
but when I try and pass in the other html to replace that section like this:
document.getElementById('demo').innerHTML =
'<div id="tlkio" data-channel="regerhtrh" data-theme="theme--night" style="width:100%;height:400px;"></div><script async src="https://tlk.io/embed.js" type="text/javascript"></script>';
it does not work. I don't think it is a quotation issue because I wrapped the outsides of it with single quotes. not sure what else to try. Below is the full html and I would appreciate any help!
<!doctype html>
<html>
<head>
<script type="text/javascript">
function init () {
// when a message is received from the page code
window.onmessage = (event) => {
if (event.data) {
console.log("HTML Code Element received a message!");
insertMessage(event.data);
}
}
}
// display received message
function insertMessage(msg) {
document.getElementById('demo').innerHTML =
'<div id="tlkio" data-channel="regerhtrh" data-theme="theme--night" style="width:100%;height:400px;"></div><script async src="https://tlk.io/embed.js" type="text/javascript"></script>'
;
}
</script>
</head>
<body onload="init();" style="background-color:lightgray;">
<h1>HTML Component Test</h1>
<p id="demo">
should put html here
</p>
</body>
</html>
The major issue is the </script> closing tag in your code. It closes YOUR block, not the block you are inserting.
You have to do so:
var myHtml = "<div id='tlkio' data-channel='regerhtrh' data-theme='theme--night' style='width: 100%; height:400px;'></div><script async src='https://tlk.io/embed.js' type='text/javascript'></scr"+"ipt>";
Second, script you insert with innerHTML wont run. Use document.createElement('script') instead
UPDATE
Here is the jsFiddle: https://jsfiddle.net/ArtyomShegeda/62fdybc0/21/
You may consider swapping the Quotes used:
function insertMessage(msg) {
var myHtml = "<div id='tlkio' data-channel='regerhtrh' data-theme='theme--night' style='width: 100%; height:400px;'></div><script async src='https://tlk.io/embed.js' type='text/javascript'></script>";
document.getElementById('demo').innerHTML = myHtml;
}
This may add it, yet may not render it. You might consider creating the elements and appending them.
function insertMessage(msg) {
var tlkio = document.createElement("div");
tlkio.style.width = "100%";
tlkio.style.width = "400px";
tlkio.setAttribute('data-channel', 'regerhtrh');
tlkio.setAttribute('data-theme', 'theme--night');
var tlkScript = document.createElement("script");
tlkScript.src = 'https://tlk.io/embed.js';
tlkScript.type = 'text/javascript';
tlkScript.async = true;
document.getElementById('demo').append(tlkio, tlkScript);
}
Based on some research here: load scripts asynchronously, it may be best to append the script to the <head>.
Hope that helps.
Update 1
Per your fiddle, once updated, it is working as you suggested: https://jsfiddle.net/Twisty/62fdybc0/7/
The following is added to #myDIV element:
<div style="width: 100%; height: 400px;" data-channel="regerhtrh" data-theme="theme--night"></div><script src="https://tlk.io/embed.js" type="text/javascript" async="async"></script>

Including <div></div> in a library

I have a few "div" sections that are called by my Javascript function using document.getElementById('ID_NAME').style.display='block'.
My question, is there a way to include these "div's" in a .js, .css or another type of library sourced from my header?
If I copy and paste the div code directly into the head it works fine, however, when I try to include it in my .js or .css libraries it wont execute.
CODE
<script type="text/javascript>
function myFunction() {
var a = window.location.href;
var b = "http://www.myblog.com/";
if (a == b) {
setTimeout(function(){
document.getElementById('EXAMPLE1').style.display='block';}, 3000);}}
window.onload = myFunction();
</script>
<div id="EXAMPLE1" class="offer_content">
<embed src="http://www.domain.com/" width="100%"
height="100%">
</div>
I know there has to be a way to insert "div" code into a library. I need some of my clients to "src" it into their own websites easily.
Much appreciated Stack community!
Jon
In another separate JS file, divs.js:
divs.js
function changeDiv(){
document.getElementById('EXAMPLE1').style.display='block';
}
index.html
<script src="divs.js"></script>
<script type="text/javascript">
function myFunction() {
var a = window.location.href;
var b = "http://www.myblog.com/";
if (a == b) {
setTimeout(changeDiv, 3000);
}
window.onload = myFunction();
</script>
<div id="EXAMPLE1" class="offer_content">
<embed src="http://www.domain.com/" width="100%"
height="100%">
</div>
Also, there seems to be syntax errors in your code. Try to run this file with a JS console (use something like "Firebug") for debugging purposes.
I wanted to post that I finally worked this problem out. While my Javascript library wouldn't support code with some code in it, I was able to convert everything with DOM.
OLD CODE::
<div id="EXAMPLE1" class="offer_content">
<embed src="http://www.domain.com/" width="100%"
height="100%">
</div>
NEW CODE::
var embed = document.createElement('embed');
embed.setAttribute("src", "http://www.domain.com/");
embed.setAttribute("width", "100%");
embed.setAttribute("height", "100%");
var content = document.createElement('div');
content.id = 'EXAMPLE1';
content.className = 'offer_content';
content.appendChild(embed);
document.getElementsByTagName('body')[0].appendChild(content);

Can't update iframe content with jquery

iframe is loaded dynamically into container div inside function.
With cc.text(content); I try to update #code content.
I check changed text in runtime, it's updated but on screen value remains the same.
I am not a javascript pro, so any comments are welcome:
function ShowEditor(content) {
var url = "XmlEditor/Editor.htm";
slHost.css('width', '0%');
jobPlanContainer.css('display', 'block');
frame = $('<iframe id="' + jobPlanIFrameID + '" src="' + url + '" class="frame" frameborder="0" />');
frame.appendTo(jobPlanIFrameContainer);
$(frame).load(function () {
var ifr = frame[0];
var doc = ifr.contentDocument || ifr.contentWindow.document;
var jdoc = $(doc);
var cc = jdoc.contents().find("#code");
// var tst = cc.text();
// alert(tst);
cc.text(content);
});
}
I get the text in commented code, but fail to update #code content.
iframe holds the following html where I omit details inside head and script:
<!doctype html>
<html>
<head></head>
<body>
<form>
<textarea id="code" name="code">some texts</textarea>
</form>
</body>
</html>
Your XML editor doesn't read more than once what's in the textarea.
A simple solution would be to generate in javascript the iframe content with the desired textarea content instead of loading it and then try to change the textarea content.
In fact (depending on the capacities of your XML Editor), you probably can do that directly in a generated text area instead of using a whole iframe to do it.

why call flash function from javascript work but FileReference don't work in flash?

I need call flash function from javascript. I use flash.external and addCallback to do this. all things work well but when I use FileReference in my flash, function did not open my browser ...
please see below describtion:
I call my function in javascript with this code:
<input type="button" value="Browse" onclick="sendToFlash('Hello World! from HTML');" />
you can see all my HTML as below:
<html>
<head>
<title>Upload test</title>
</head>
<script>
function hello (size) {
alert ("size hast: " + size);
}
function sendToFlash(val){
var flash = getFlashObject();
flash.new_browser(val);
}
var flash_ID = "Movie2";
var flash_Obj = null;
function getFlashObject(){
if (flash_Obj == null){
var flashObj;
if (navigator.appName.indexOf( "Microsoft" ) != -1){
flashObj = window[flash_ID];
}
else{
flashObj = window.document[flash_ID];
}
flash_Obj = flashObj;
}
return flash_Obj;
}
</script>
<body>
<center>
<embed width="560" height="410" type="application/x-shockwave-flash"
flashvars="sampleVars=loading vars from HTML"
salign="" allowscriptaccess="sameDomain" allowfullscreen="false" menu="true" name="Movie2"
bgcolor="#ffffff" devicefont="false" wmode="window" scale="showall" loop="true" play="true"
pluginspage="http://www.adobe.com/shockwave/download/index.cgi?P1_Prod_Version=ShockwaveFlash"
quality="high" src="Movie2.swf">
</center>
<input type="button" value="Browse" onclick="sendToFlash('Hello World! from HTML');" />
</body>
</html>
when I click Browse in html page, javascript call sendToFlash function and SendToFlash function send my string (Hello World! from HTML) to flash.
in flash I get this string with below code:
resultsTxtField.text = "";
uploadButton.onPress = function () {
return browse_file("Hello World! from Flash");
}
import flash.external.*;
ExternalInterface.addCallback("new_browser", this, browse_file);
function browse_file (my_test_val) {
_root.resultsTxtField.text = "val: " + my_test_val;
import flash.net.FileReference;
var fileTypes:Array = new Array();
var imageTypes:Object = new Object();
imageTypes.description = "Images (*.jpg, *.jpeg, *.gif, *.png)";
imageTypes.extension = "*.jpg; *.jpeg; *.gif; *.png";
fileTypes.push(imageTypes);
var fileListener:Object = new Object();
var btnListener:Object = new Object();
var fileRef:FileReference = new FileReference();
fileRef.addListener(fileListener);
fileRef.browse(fileTypes);
fileListener.onCancel = function(file:FileReference):Void
{
_root.resultsTxtField.text += "File Upload Cancelled\n";
}
fileListener.onSelect = function(file:FileReference):Void
{
_root.resultsTxtField.text += "File Selected: " + file.name + " file size: "+ file.size + " file type: " + file.type;
getURL("javascript:hello("+file.size+");");
}
}
I have only one Scene and this code is on root of this Scene. and I have one movie clip named uploadButton and has only a rectangle that work as button in this sample.
when you click on rectangle browse_file("Hello World! from Flash"); called and a browser open that you can select a photo to upload.
when you click on browse in html same process must do but as you see variable send to function but browser to select a photo did not open any more.
I try several ways. for example I set new function to open only picture browser or set new Scene or use gotoAndPlay and more but there is another problem.
you can download my source from below link:
http://www.4shared.com/zip/YTB8uJKE/flash_uploader.html
note that javascript onclick="sendToFlash('Hello World! from HTML');" don't work in direct opening. you must open it in localhost.
I'll be so so happy for any clue.
thanks so much
Reza Amya
You can't programmatically call browse(), it has to be from a mouse click inside Flash: http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/flash/net/FileReference.html#browse()
In Flash Player 10 and Flash Player 9 Update 5, you can only call
this method successfully in response to a user event (for example, in
an event handler for a mouse click or keypress event). Otherwise,
calling this method results in Flash Player throwing an Error
exception.
after a day reading I know that it is impossible for security reasons.
then you can't open file reference with addCallback javascript code any way. for more information read fileReference browse from js, simulate keypress in flash workaround
Thanks again
Reza Amya

Categories

Resources