How to bootstrap an AngularJS app loaded inside a friendly IFRAME - javascript

I want to load an AngularJS app inside a “friendly” IFRAME (due to SEO reasons).
See example code here:
https://jsfiddle.net/tomsoderlund/mssca32k/
var embedDiv = document.getElementById('weld-embed');
// Create friendly IFRAME
var newIframe = document.createElement('iframe');
newIframe.src = 'about:blank';
newIframe.width = '100%';
newIframe.height = '100%';
newIframe.frameBorder = '0';
embedDiv.appendChild(newIframe);
// Create contents inside
var htmlContent = '<!doctype html>'
// ...
+ '<\/body><\/html>';
newIframe.contentWindow.document.write(htmlContent);
The AngularJS app doesn’t start up, probably because document.ready doesn’t trigger in a normal fashion. Can I bootstrap/force the AngularJS code to start up?

The problem was solved by:
Moving from JSFiddle to a simpler web structure.
Loading htmlContent from a separate template.html HTML file*.
Bootstrapping AngularJS from within template.html**.
*Code from point 2 above (adapted from “HTTP GET request in JavaScript?”):
var httpGetAsync = function (theUrl, callback) {
var xmlHttp = new XMLHttpRequest();
xmlHttp.onreadystatechange = function () {
if (xmlHttp.readyState == 4 && xmlHttp.status == 200) {
callback(xmlHttp.responseText);
}
}
xmlHttp.open("GET", theUrl, true); // true for asynchronous
xmlHttp.send(null);
}
httpGetAsync('/template.html', function (htmlContent) {
newIframe.contentWindow.document.write(htmlContent);
});
**Code from point 3 above:
<script type="text/javascript">
angular.bootstrap(document, ['myAngularModule']);
</script>

Related

xmlhttprequest load specific div from an external HTML

I am using xhlhttprequest to load an external html file. However I am trying to figure out how to load only a speicific DIV from that html file.
My external page is helpFile.html- it has dozens header <DIV>s, an each header DIV is a specific help section. On different pages, I want to be able load a specific section? How could I do this? As an example, on the dashboard.html page is a help ? icon, that when the user clicks on it, it will load just the helpFile.html#dashboard section out of the main helpFile.html page - the content would be loaded into a bootstrap modal.
Here is my code to retrieve the entire page, but how can I just retrieve the needed section.
<script>
var request;
function sendInfo() {
var url = "helpFile.html";
if (window.XMLHttpRequest) {
request = new XMLHttpRequest();
} else if (window.ActiveXObject) {
request = new ActiveXObject("Microsoft.XMLHTTP");
}
try {
request.onreadystatechange = getInfo;
request.open("GET", url, true);
request.send();
} catch (e) {
alert("Unable to connect to server");
}
}
function getInfo() {
if (request.readyState == 4) {
var val = request.responseText;
document.getElementById('helpModal').innerHTML = val;
}
}
</script>
Use DOMParser and look for the element
if (request.readyState == 4 && request.status == 200) {
var parser = new DOMParser();
var doc = parser.parseFromString(request.responseText;, "text/html");
var dashboardElement = doc.querySelector("#dashboard");
document.getElementById('helpModal').innerHTML = dashboardElement.innerHTML;
}

Using AJAX to change content - when users navigate to direct URL new content is not displayed

I want to create a page that refreshes content within a div async alongside providing a user with an anchor to enable direct access to the content within the div. (e.g. www.website.co.uk/#page1)
I've managed to make it so that the content can be updated for 1 page, however, if I add multiple pages it stops working
Additionally - if I was to navigate to the URL website.co.uk/#page1 it wont display #page1.
Can anyone help?
This is my current code:
HTML :
<h5> Test</h5>
<h5> Test2</h5>
JS :
<script type="text/javascript">
var routes = {
'#page1' : '{{site.url}}/page1'
'#page2' : '{{site.url}}/page2'
};
var routeHandler = function( event ) {
var hash = window.location.hash,
xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
document.getElementById("div1").innerHTML = xhttp.responseText;
}
};
xhttp.open("GET", routes[hash], true);
xhttp.send();
};
window.addEventListener('hashchange', routeHandler);
window.addEventListener('load', function() {
var hash = window.location.hash;
if (routes.hasOwnProperty(hash)) routehandler();
});
</script>

jQuery, .load, javascript, (prevent scroll up), XMLHttpRequest, .innerHTML, CSS/JS NOT WORKING

When using this code no CSS/Javascript works (It just loads the HTML):
function functionName(limit) {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
var text = xhttp.responseText;
document.getElementById("content").innerHTML = "";
document.getElementById("content").innerHTML = text;
}
}
xhttp.open("GET", "?x=test&limit=" + limit, false);
xhttp.send();
}
When using jQuery CSS/Javascript works, now the problem is that the page scrolls up when loading the content.
$('#content').load('?x=test&limit=" + limit);
What I want is a way to load an URL to a DIV, where CSS and Javascript works.
And like .innerHTML I want to load the content without scrolling to the top.
Hope for help, yesterday i googled for 6-8 hours, and im a google-fu guru =)
Still got the same problem!
When using XMLHttpRequest and .innerHTML it loads the HTML (without scrolling up to the start of the div). But no Javascript or CSS works...
And with this it loads Javascript and CSS when .load'ing. But it scrolls up to the start of the div.
$('#content').load("?x=test&limit=" + limit);
function functionName(limit) {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
var ele = document.createElement("script");
ele.src = "js/some-js-ajax.js";
document.body.appendChild(ele);
var text = xhttp.responseText;
document.getElementById("content").innerHTML = "";
document.getElementById("content").innerHTML = text;
}
}
xhttp.open("GET", "?x=test&limit=" + limit, false);
xhttp.send();
}
When adding:
var ele = document.createElement("script");
ele.src = "js/some-js-ajax.js";
document.body.appendChild(ele);
.innerHTML works with CSS and Javascript, but now it scrolls up to the start o fthe div again. Not staying in the scrolled place where you were before the functionName(limit) load ....

for some reason, document.getElementById().innerHTML is not working?

i have a span with the same value..
echo "<span id='msgNotif1' class='badge' style='position:relative;right:5px;bottom:10px;'>".$number."</span>";
where $number have a value..
and my js code is..
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
var val = xmlhttp.responseText;
//alert(val);
document.getElementById("msgNotif1").innerHTML = val;
//document.getElementById("msgNotif2").innerHTML = val;
alert(val);
//document.getElementById("msgNotif3").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("GET", "some page", true);
xmlhttp.send();
the problem is the value still remains and do not change,
trying to uncomment the first alert shows an alert with the right value, but when i try to comment it the second alert never executed, giving me an idea that the document.getelementbyid().innerhtml is the one that is not working, been with this for a few hours,
any help will be appreciated.
thanks in advance
Your error message Cannot set property 'innerHTML' of null" means that:
document.getElementById("msgNotif1")
is returning null. That can happen for several possible reasons:
There is no element in your page with id="msgNotif1".
You are calling this code before your document has finished loading and thus the element with id="msgNotif1" has not yet loaded. This can commonly happen if you execute your code in the <head> section of the document rather than at the very end of <body> or in response to the DOMContentLoaded event.
Your content is dynamically loaded (not in the original page HTML) and you are calling document.getElementById("msgNotif1") before your dynamic content has been loaded.
You have some HTML errors which are preventing the proper parsing of your HTML that contains the element with id="msgNotif1".
For a general purpose description of how to run Javascript after the current page has been loaded without using a framework like jQuery, see this answer: pure JavaScript equivalent to jQuery's $.ready() how to call a function when the page/dom is ready for it
You are receiving this error in your console because it doesn't exist at the time your script is running. This can be caused if the element hasn't been loaded when your script is running, if your IDs aren't the same, or if the element doesn't exist in your html. If you are referencing the element before it loads, add a function that executes when your page loads.
You can use JQuery
$(document).ready(function(){
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
var val = xmlhttp.responseText;
//alert(val);
document.getElementById("msgNotif1").innerHTML = val;
//document.getElementById("msgNotif2").innerHTML = val;
alert(val);
//document.getElementById("msgNotif3").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("GET", "some page", true);
xmlhttp.send();
});
or with pure Javascript to create the event.
window.onload = function(){
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
var val = xmlhttp.responseText;
//alert(val);
document.getElementById("msgNotif1").innerHTML = val;
//document.getElementById("msgNotif2").innerHTML = val;
alert(val);
//document.getElementById("msgNotif3").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("GET", "some page", true);
xmlhttp.send();
};
Valid points have been brought up in that doing Ajax requests with pure Javascript takes much more code than if you were to use JQuery. This is the reason why I (and many others) use JQuery for all the Ajax requests performed. JQuery has many methods for Ajax that will save a lot of time and code and in the long run will reduce your file size by a few bytes since, with JQuery, the code is reused.

Load html contents of a given url and place exactly there (like document.write()) in JavaScript

I want to write a JavaScript code that load HTML contents of a given URL and place the loaded HTML code exactly where the script is placed. (maybe this looks like functionality of the iframe tag, but i dont want "iframe tag" become a medium. i just want to load the html code and place it there without adding any container or extra parent)
something like this:
var url = "http://example.com/";
var html = loadhtmlcontents(url); // something like simplexml_load_file($url) for php and xml
document.write(html); // somthing like saveHTML() in DOMDocument class of php
I've tried AJAX approach but it doesn't work:
var xmlhttp=new XMLHttpRequest();
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.wirte( xmlhttp.responseText);
}
}
xmlhttp.open("GET", Url, false );
xmlhttp.send();
could you please give me an equivalent or correction to these? (pure JS approach is preferred to JQuery for me in this situation)
Getting the current script tag is possible, but here's another approach (keep in mind it replaces the entire element with the id tag):
In the body tag:
<script id='test'>docWrite('test', '/echo/html')</script>
Javascript declaring a new function:
function docWrite(id, url) {
var xmlhttp = new XMLHttpRequest(),
_id = id;
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState == 4
&& xmlhttp.status == 200) {
var el = document.getElementById(_id),
textnode = el.firstChild,
div = document.createElement('div');
div.id = _id;
div.appendChild(textnode);
el.parentNode.insertBefore(div, el.nextSibling);
el.parentNode.removeChild(el);
console.log(xmlhttp.responseText);
}
}
xmlhttp.open("GET", url, false );
xmlhttp.send();
}
http://jsfiddle.net/dpgk1Lx2/
Here, all I'm doing is copying the contents of the id-related tag (there is no responseText to display). In your usage, you would do this instead:
function docWrite(id, url) {
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState == 4
&& xmlhttp.status == 200) {
var el = document.getElementById(_id)
div = document.createElement('div');
div.id = _id;
div.appendChild(xmlhttp.responseText);
el.parentNode.insertBefore(div, el.nextSibling);
el.parentNode.removeChild(el);
}
}
xmlhttp.open("GET", url, false );
xmlhttp.send();
}
I know you are looking for a jQuery-less version... but I'm going to post this first... just to indicate how simple it is (and it works around browser differences in making AJAX calls, handling callbacks etc. for you).
<div id="someID"></div>
<script>$('#someID').load('someurl.html');</script>

Categories

Resources