This is not a duplicate question for these reasons:
I am asking about how to replace the entire HTML document with JavaScript without jQuery or any other fancy extensions to JavaScript. Some of the other questions that are similar to this question deal with specific things like AJAX or jQuery.
I am NOT asking about why document.write() only appends to the page. Perhaps the pure JavaScript solution I am looking for may incorporate that function, but it cannot only be that since it is inadequate by itself.
What I am looking to do is overwrite a webpage as it is displayed in the browser with only HTML. The function document.write() only appends whatever argument is passed to it to the document's body. The property document.documentElement.outerHTML can be read from, but unlike when it is used on a page's child elements, cannot be written to, and even if it could, it would leave the DOCTYPE untouched.
I am working on a bookmarklet, so this JavaScript would not run in the page, meaning there is no problem with the script being overwritten while it is running. It could also be run in the browser's developer tools.
As an example, suppose I have about:blank opened in my browser. The contents of the DOM would look like this:
<html>
<head></head>
<body></body>
</html>
I want to be able to overwrite it with whatever string I want. So, for instance, I could make it look like this:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Example</title>
</head>
<body>
<p>This is an example.</p>
</body>
</html>
How can I achieve that sort of overwrite of a document?
Try this:
function one() {
document.write('<html><body><pre>the first html</pre></body></html>');
document.close(); // this makes the difference
}
function two() {
document.write('<html><body><pre>the second html</pre></body></html>');
document.close();
}
Refer to linstantnoodles' answer in question document.write() overwriting the document?, the document.open is implicitly called before the document.write is called, but the document.close doesn't, and
document.write() when document is closed = rewrite the document;
document.write() when document is open = append to the document.
You can use document.implementation.createDocumentType to rewrite the doctype and document.getElementsByTagName to get the DOM elements, then rewrite with innerHTML and setAttribute.
var newDoctype = document.implementation.createDocumentType('html','-//W3C//DTD XHTML 1.0 Transitional//EN','http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtdd');
document.doctype.parentNode.replaceChild(newDoctype,document.doctype);
document.getElementsByTagName('html')[0].setAttribute('xmlns', 'http://www.w3.org/1999/xhtml');
var doc = document.getElementsByTagName('html')[0];
doc.getElementsByTagName('head')[0].innerHTML = '<title>Example</title>';
doc.getElementsByTagName('body')[0].innerHTML = '<p>This is an example.</p>';
<!DOCTYPE html>
<html>
<head>
</head>
<body>
</body>
</html>
Edit:
Updated to include comments by Xweque and xmlns attribute.
document.write('Some Text')
document.write rewrites the page's code.
Related
I don't know how to declare a variable here in javascript. I have an example situation that if the paragraph is equals to a, the alert will popup.
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<p id="sample">a</p>
</body>
</html>
<script type="text/javascript">
var sample = getElementById('sample');
if (sample == "a") {
alert("Correct")
};
</script>
You're declaring your variable just fine, however if you want the text within the element, you also need to use the innerHTML property. And when you use the getElementById method, you need to use it on the document object like document.getElementById:
var sample = document.getElementById('sample');
if (sample.innerHTML == "a") {
alert("Correct")
};
<p id="sample">a</p>
sample is a variable and you are correct but it is storing a reference to a DOM Element with id sample. To get the inner html of that you need
var sample = getElementById('sample').innerHTML;
Also, use === over == for no casting etc. Refer here
I will recommend you to have a quick look at JS from w3schools and then move to MDN. Nobody will report you here if you show your efforts, so relax :).
Your declaration is fine, but the assignment part is missing document as the object which has the .getElementById method. Then, once you have the reference to the element, you then need to access its content with .textContent (you can't compare the entire element to a value that the element might contain). As a side note on this, when the string you wish to set/get doesn't contain any HTML, you should use .textContent so that the browser doesn't parse the string for HTML unnecessarily. Often, people will suggest that the content of an element should be gotten/set using .innerHTML and, while that will work, it's wasteful if the string doesn't contain any HTML.
Also, the <script> must be located within the head or the body, not outside of them. I would suggest placing it just prior to the closing body tag so that by the time the processing reaches the script, all of the HTML elements have been parsed into memory and are available.
Lastly (and this is really just a side point), an HTML page also needs the title element to have something in it, otherwise it won't be valid. While browsers don't actually do HTML validation, it's important to strive for valid HTML so that you can be sure that your pages will work consistently across all devices. You can validate your HTML at: http://validator.w3.org.
<!DOCTYPE html>
<html>
<head>
<title>Something Here</title>
</head>
<body>
<p id="sample">a</p>
<script type="text/javascript">
var sample = document.getElementById('sample');
if (sample.textContent == "a") {
alert("Correct")
};
</script>
</body>
</html>
So what i am trying to achieve is to manipulate a javascript variable from a website, so that when I load the page it changes to a value I have pre determined (inmyscript.js).
In Safari's extension builder I have the following setup:
Access Level: All (To make sure it is running correctly for the time being)
Start Scripts: jquery.min.js (the jquery script)
End Scritps: myscript.js (myscript)
The Start Scripts, will load the jquery script, as I want to use jquery for some DOM manipulation.
The End Script is the script which contains an overwrite for the variable I am trying to change in the html document.
Currently myscript.js looks like:
$(document).ready(function(){
var numberImThinkingOf = 999;
});
For an example of what I am trying to do: The following page, prints out the value of numberImThinkingOf, by creating a new paragraph element every time the submit button is pressed.
So with out the extension it will print out
Value: 5
Value: 5
Value: 5
If pressed three times.
However I want my Safari Extension to change the default value of the numberImThinkingOf variable once all DOM elements are loaded, to that specified in myscript.js So that when I press the submit button it will output:
Value: 999
Ideally I don't want to manipulate the DOM so that it inserts another script element. I originally though that javascript attached variables to the window object. But I guess I was wrong. Event if I have a script such as
$(document).ready(function(){
alert(numberImThinkingOf)
});
It returns undefined. :( Any help would me much appreciated.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<script>
var numberImThinkingOf = 5;
function whatNumber(){
var newElement = document.createElement("p");
newElement.textContent = "Value: "+numberImThinkingOf;
document.body.insertBefore(newElement, document.body.firstChild);
}
</script>
</head>
<body>
<input type="submit" value="Continue →" onclick="whatNumber()" />
</body>
</html>
I believe your script and the page get different window objects, to avoid unexpected contamination. Here's what the Safari Extensions Development Guide says:
Injected scripts have an implied namespace—you don’t have to worry about your variable or function names conflicting with those of the website author, nor can a website author call functions in your extension. In other words, injected scripts and scripts included in the webpage run in isolated worlds, with no access to each others’ functions or data.
It sounds like you need to attach this variable to the DOM in some fashion, perhaps as an attribute of a tag.
Content scripts are sandboxed, if you want to access parent page variables you have to inject <script> tag with your code. You can find some examples here.
I'm working through some javascript examples, and I just did this one:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Page title</title>
<script type="text/javascript">
function displayText()
{
document.getElementById('targetDIV').innerHTML = "You're using Javascript";
}
</script>
</head>
<body onload="displayText()">
<h2>This should be before the other text.</h2>
<div id="targetDIV">
</div>
</body>
</html>
OK. Very basic, I know-but I realized I was confused about the "why" of some things. Could it be accurate to say that:
Function=WHAT will happen.
The call (the body onload...)= WHEN it will happen.
and div id="targetDIV" = WHERE it will happen
I know this is the case in this example, but in general is that the way things work in Javascript?
Yes, that's a pretty good working model to carry in your head.
onload for the body is called an Event and many objects issue events. Your function displayText is called in response to the onload Event and is therefore an event handler.
The code inside your function can do anything, but in this case it dynamically loads some text into a tag on your page.
There are a couple of other things worth pointing out at this point. You access the tag using document.getElementById. document is variable available to you in Javascript which contains a model of the page called the DOM or document object model. This is extremely powerful as it presents a hierarchical layout of everything on your page and allows you to manipulate the contents.
getElementById() is a very useful function which searches the DOM tree and returns the object which has the ID that you specify, it's a sort of search. The text gets to your tag because you added the targetDIV id to the DIV tag and therefore you could find it via the DOM function.
Welcome to programming in Javascript. Now you have a goood working model you'll find loads of really clever things you can do and your life as a web programmer will never be the same again.
Sound good to me.
I have found several other questions here on S.O. (and the web in general) that ask roughly this same question, but the answers always seem to suggest other ways of structuring code that avoid the need for addressing this underlying issue.
For example, many people suggest (and a good suggestion, I agree) to put your code in the jquery load method's callback, on the calling page and not the called page. However I have unique scripts that may appear in certain resources, so I would not want to do that for every load and nor do I necessarily know what these scripts will be.
Here is a test setup to demonstrate what I'm trying to do. The short summary is that when I load partial.htm from main.htm, its script does not fire.
main.htm:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>main file</title>
</head>
<body>
<ul id="links">
<li>some page1</li>
<li>some page 2</li>
<li>some other partial page</li>
</ul>
<div id="panel" style="display:none; padding:20px; background-color:#CCC;">
LOADED CONTENT WILL GO HERE
</div>
<script type="text/javascript" src="/path/to/jquery-1.3.2.min.js"> </script>
<script type="text/javascript">
$(function(){
$('#links a').click(function() {
var $panel = $('#panel');
$panel.show();
$panel.html('Please wait...');
var href = $(this).attr('href');
$('#panel').load(href + ' #content');
return false;
});
});
</script>
</body>
</html>
OK, very simple functionality on this page. Imagine there are many more links, and some of them may require scripting while others do not.
Here is partial.htm:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>partial file</title>
</head>
<body>
<div id="content">
<p>Hey, I am the partial file!</p>
<script type="text/javascript">
alert('I am some JS in the partial file! But sadly I do not execute...');
</script>
</div>
<div>
I am some other content on the page that won't be included by jquery.load()...
</div>
</body>
</html>
Notice that my script in partial.htm does not fire. So, my question remains: how to get this to fire, excluding any answers that tell me to put this in the .load() method's callback. (This would be because I may not have the fore-knowledge of which scripts these partial pages may contain or require!)
Thank you!
Update #1:
I suppose an acceptable answer is simply "you can't." However, I'd like to know if this is definitively the case. I haven't been able to find anything that officially states this yet.
Also, when I use firebug to inspect the panel region afterwards, there is no script element present at all. It is as if it is being parsed out by load.
Update #2:
I've narrowed this down to be a problem only when using the selector as part of the href. Loading the entire "somepage.html" will execute the script, but loading "somepage.html #someregion" does not.
$panel.load('somepage.html'); // my script fires!
$panel.load('somepage.html #someregion'); // script does not fire
I'm going to try and hunt down why this may be the case in the jquery source...
Well it seems that this is by design. Apparently to make IE happy, the rest of us suffer. Here's the relevant code in the jquery source:
// See if a selector was specified
self.html( selector ?
// Create a dummy div to hold the results
jQuery("<div/>")
// inject the contents of the document in, removing the scripts
// to avoid any 'Permission Denied' errors in IE
.append(res.responseText.replace(/<script(.|\s)*?\/script>/g, ""))
// Locate the specified elements
.find(selector) :
// If not, just inject the full result
res.responseText );
I'm wondering if, instead of just stripping out the scripts, I could modify the jquery source to include them in some other way that makes IE happy? I still have yet to find anything else on the web discussing this matter, I'm sure I'm not the only person stumped by this?
I have run across issues before with IE not running injected <script>s that didn't contain the defer attribute. This discussion thread has some good information about the topic: innerHTML and SCRIPT tag
I read that you should define your JavaScript functions in the <head> tag, but how does the location of the <script> (whether in the <head>, <body>, or any other tag) affect a JavaScript function.
Specifically, how does it affect the scope of the function and where you can call it from?
Telling people to add <SCRIPT> only in the head sounds like a reasonable thing to do, but as others have said there are many reasons why this isn't recommended or even practical - mainly speed and the way that HTML pages are generated dynamically.
This is what the HTML 4 spec says :
The SCRIPT element places a script
within a document. This element may
appear any number of times in the HEAD
or BODY of an HTML document.
And some sample HTML. Doesn't it look pretty all formatted here :)
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
<HTML>
<HEAD>
<TITLE>A document with SCRIPT</TITLE>
<META http-equiv="Content-Script-Type" content="text/tcl">
<SCRIPT type="text/vbscript" src="http://someplace.com/progs/vbcalc">
</SCRIPT>
</HEAD>
<BODY>
<SCRIPT type="text/javascript">
...some JavaScript...
</SCRIPT>
</BODY>
</HTML>
And something to look forward to in HTML 5 :
New async attribute in <SCRIPT> :
Note: There are ways [sic] a script can be
executed:
The async attribute is "true": The
script will be executed asynchrously
with the rest of the page, so the
script will be executed while the page
continues the parsing.
The async attribute is "false", but
the defer attribute is "true": The
script will be executed when the page
is finished with the parsing.
The normal rules of play still stand; don't use stuff before it's defined. :)
Also, take note that the 'put everything at the bottom' advice isn't the only rule in the book - in some cases it may not be feasible and in other cases it may make more sense to put the script elsewhere.
The main reason for putting a script at the bottom of a document is for performance, scripts, unlike other HTTP requests, do not load in parallel, meaning they'll slow down the loading of the rest of your page. Another reason for putting scripts at the bottom is so you don't have to use any 'DOM ready' functions. Since the script tag is below all elements the DOM will be ready for manipulation!
EDIT: Read this: http://developer.yahoo.com/performance/rules.html#js_bottom
One of the aspects of placement is performance. See this fine article within the YSlow discussion for why it's sometimes recommended you put them at the bottom of the document.
As for issues of scope, the usual visibility rules for Javascript (vars defined inside or outside of functions, local, global, closures, etc.) are not affected so far as I know.
Position of script tag does matter.
If you bind a Function with document Element then the document element has to be loaded first before we implement function. suppose getTeachers() is function in getTeachers.js file.
This will give you an error:
<html xmlns="http://www.w3.org/1999/xhtml">
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Unit Teachers</title>
<head>
<script type="text/javascript" src="getTeachers.js"></script>
<script type="text/javascript">
document.getElementById("buttonId").onclick=function(){getResults()};
</script>
</head>
<body>
<form>
<input type = "button" id="buttonId" value = "Press for Results" /><br />
</form>
<span id="results" /></span>
</body>
</html>
It gives error before head is loaded first and it cannot find element with id specified.
The below code is correction:
<html xmlns="http://www.w3.org/1999/xhtml">
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Unit Teachers</title>
<head>
<script type="text/javascript" src="getTeachers.js"></script>
</head>
<body>
<form>
<input type = "button" id="buttonId" value = "Press for Results" /><br />
</form>
<script type="text/javascript">
document.getElementById("buttonId").onclick=function(){getResults()};
</script>
<span id="results" /></span>
</body>
</html>
If your script refers to an ID on the page and the page has not been rendered (i.e. script is before HTML, or your script is executed with onload, rather then the DOM is ready) you can also get an error.
It doesn't. Most programming framework scatter scripts all throughout the page. I've only rarely seen problems because of that (and only from older browsers).
If you pull Javascripts in through XMLHttpRequest, like Diodeus said, it probably won't work. In my case, there was no error, the browser just ignores the new script(s).
I ended up using this, not terribly elegant but works for me so far:
http://zeta-puppis.com/2006/03/07/javascript-script-execution-in-innerhtml-the-revenge/
How to use execJS: http://zeta-puppis.com/2006/02/23/javascript-script-execution-in-innerhtml/
Note: Watch out for < in this line: for(var i=0;i<st.length; i++)
If you have an inline script (outside functions) located before functions it may call, you may get an error because they may not be not available yet. Not saying it is always going to happen, just that it may depending on browser type or version.
Javascript's scoping rules are similar to perl - you can call any function at the current or any higher scope level. The only restriction is that the function has to be defined at the time you call it. The position in the source is irrelevant - only the position in time matters.
You should avoid putting scripts in the <head> if possible as it slows down page display (see the link Alan posted).