How to get the title of HTML page with JavaScript? - javascript

How can I get the title of an HTML page with JavaScript?

Use document.title:
console.log(document.title)
<title>Title test</title>
MDN Web Docs

Put in the URL bar and then click enter:
javascript:alert(document.title);
You can select and copy the text from the alert depending on the website and the web browser you are using.

Can use getElementsByTagName
var x = document.getElementsByTagName("title")[0];
alert(x.innerHTML)
// or
alert(x.textContent)
// or
document.querySelector('title')
Edits as suggested by Paul

this makes the h1 element the page title. this shows how capable can be javascript for small and big projects.
document.getElementById("text").innerText = document.title;
<title>hello world</title>
<h1 id="text"></h1>

Related

Find and replace button works but takes me to a new page

I'm a beginner in JavaScript and I've been working on this project which uses regular expressions to find and replace particular strings on a text.
I'd say it's working pretty well, but when I click the 'go' button in order to replace the string, it does so, but takes me to a new page which only contains the replaced string. The console says something about "Quirks mode"? not sure what that is.
Here's my code:
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>findNreplace</title>
</head>
<body>
<textarea name="input" id="inputText">
</textarea>
<p id="projectedText"></p>
<label for="find">Find: </label>
<input type="text" id="find">
<label for="replace">Replace: </label>
<input type="text" name="" id="replace">
<input type="button" value="Go" id="commit">
<script src="script.js"></script>
</body>
</html>
document.getElementById("commit").onclick=findNreplace; //set up go button
//variables
var textToShow = document.getElementById("inputText");
var projected = document.getElementById("projectedText");
var toFind = document.getElementById("find");
var toReplace = document.getElementById("replace");
// set up text area to project the input into the paragraph
textToShow.addEventListener('input',updateValue);
function updateValue(text) {
projected.textContent=text.target.value;
}
// replace function
function findNreplace() {
var str = projected.innerText;
var regex = new RegExp(toFind.value, 'g')
var found = projected.innerText.match(regex);
document.write(str.replace(regex.source, toReplace.value))
console.log(regex.source);
}
;TLDR
Do not use document.write outside of a tutorial exercise to insert content into the HTML input stream during page load.
document.write, .open and .close
During page load, when the HTML parser is processing the HTML input stream, the document is open, and you can use document.write to insert content into the input stream at its current position.
When the page has finished loading from its input stream, the document is automatically closed.
If you call document.write on a closed document it will automatically open the document for you. This opening the document again resets the document to an empty state - of having no content. This is why you only see what you have written.
If the document is opened by document.write it will stay open until you explicitly call document.close. This is why if the browser displays a page loading indicator, it will remain active until document.close is called.
In most cases document.write is used in beginners' JavaScript programming course so they see results of example tasks quickly. It has a place in inserting HTML input during page load but has its limitations1.
Notes
1document.write can be used during page load to dynamically insert script tags that need to be loaded synchronously. Browsers sometimes ignore such insertions, but inserting scripts from the same domain as the HTML page is allowed.
See also Why is document.write considered a "bad practice"?
Quirks mode
The quirks mode warning is being issued because the HTML document does not start with a document type declaration. Insert the following line,
<!DOCTYPE html>
as the first line of HTML source to have the page parsed according to standards.
Appending HTML to a document.
Element.insertAdjacentHTML() invokes the HTML parser on a markup string and allows you to append HTML to a specified element.
Here's an example of using it to append HTML to a page, after document.body has been created, without using document.write:
// bodyAppend - append HTML string to body
function bodyAppend( htmlString) {
document.body.insertAdjacentHTML("beforeend", htmlString);
}
// and test
bodyAppend("<p style='color:green'>An appended paragraph</p>");
<h1>Page Header</h1>
Some existing page content.
'insertAdjacentHTML' can't be used in the head section of a page - document.body has not been created and is still set to null,
bodyAppend presented above is intended for beginners - it's just one example of a particular technique. Please read the linked documentation to understand the syntax used, and do a search for "how to modify the DOM in JavaScript" to learn more about the scope of the topic.

Dynamically create an HTML document using javascript using window

I need to create a new HTML page using javascript.
To do that I tried using the window object
let myDocument = window;
myDocument.document.write(`
<html>
<head>
<title>${title}</title>
</head>
<body><section id="print"></section></body>
</html>
`)
My problem is that I would like to generate that on the background and save the result somewhere in my project.
The user cannot see a new page open or a new window
The new HTML has to be saved
These are the two problems I have at the moment.
I can generate the page, but I could not find out how to do that on the background.
My limitation is that the project uses pure javascript so Node.js packages might not work.
Instead of document.write you can save it in a variable & use it when you want or save it through service or localStorage.
You code must be like:
const title = "Hello World!";
let myDocument =
`<html>
<head>
<title>${title}</title>
</head>
<body><section id="print"></section></body>
</html>`;
console.log(myDocument);

Disable Firefox 7.0.1 javascript in url security

It seems that firefox has disabled the ability to run a javascript: from the URL...does anybody know of a way around this?
My site requires an id pulled from the html of another site when that user is logged in. Instead of having the user search the 'view source' page I devised a javascript link to scrape it and send it to the site automagically, but it doesn't work on firefox.
The actual code I'm trying to run:
javascript:void(window.open('http://mysite.com/login?u=' + encodeURIComponent(window.location) + '&s=' + SessionId));
Scrapping the session id from the game in order to pull data for the player, nothing like a facebook hack or anything malicious.
I'd have to see your code but you really shouldn't have a problem doing what you're attempting to do. If you need another option though I have one you could try. If the content of the page you're scraping is within the same domain as your other site you could use an iframe to get the ID.
Here's some code to consider:
Your data collecting page:
<!DOCTYPE html>
<html>
<head>
<title>Disable Firefox 7.0.1 javascript in url security</title>
<script type="text/javascript">
function scrapeData() {
var frame = document.getElementById("otherPage");
var otherPagesObj = frame.contentWindow.document.getElementById("otherContent");
alert("Your data: " + otherPagesObj.innerHTML);
}
</script>
</head>
<body onload="scrapeData();">
<iframe id="otherPage" src="otherpage.htm" width="1" height="1" />
</body>
​</html>​​​​​​​​​​​​​​​​​​​​​​​​
Your page to be scraped (otherpage.htm):
<!DOCTYPE html>
<html>
<head>
<title>Other Page - Disable Firefox 7.0.1 javascript in url security</title>
</head>
<body>
<div id="otherContent">1</div>
</body>
​</html>​​​​​​​​​​​​​​​​​​​​​​​​
Using the above code you can see "1" alerted from the div of another page. This is a simple, cross-browser compatible option for what you're attempting to do.
Hope this helps.

Open a new browser window/iframe and create new document from HTML in TEXTAREA?

I'm trying to write a web application using the new offline capabilities of HTML5. In this application, I'd like to be able to edit some HTML—a full document, not a fragment—in a <textarea>, press a button and then populate a new browser window (or <iframe>, haven't decided yet) with the HTML found in the <textarea>. The new content is not persisted anywhere except the local client, so setting the source on the window.open call or the src attribute on an <iframe> is not going to work.
I found the following question on StackOverflow: "Putting HTML from the current page into a new window", which got me part of the way there. It seems this technique works well with fragments, but I was unsuccessful in getting an entirely new HTML document loaded. The strange thing is when I view the DOM in Firebug, I see the new HTML—it just doesn't render.
Is it possible to render a generated HTML document in a new window or <iframe>?
EDIT: Here's a "working" example of how I'm attempting to accomplish this:
<!doctype html>
<html>
<head>
<title>Test new DOM</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script>
function runonload() {
return $("#newcode")[0].value;
}
$(function() {
$("#runit").click(function() {
w=window.open("");
$(w.document).ready(function() {
$(w.document).html(w.opener.runonload());
});
});
});
</script>
</head>
<body>
<textarea id="newcode">
<!doctype html>
<html>
<head>
<title>New Page Test</title>
</head>
<body>
<h1>Testing 1 2 3</h1>
</body>
</html>
</textarea>
<br/>
<button id="runit">Run it!</button>
</body>
</html>
I think you are overcomplicating this...
try this:
<SCRIPT LANGUAGE="JavaScript">
function displayHTML(form) {
var inf = form.htmlArea.value;
win = window.open(", ", 'popup', 'toolbar = no, status = no'); win.document.write("" + inf + ""); } // </script>
<form>
<textarea name="htmlArea" cols=60 rows=12> </textarea> <br> <input type="button" value=" Preview HTML (New Window)" onclick="displayHTML(this.form)"> </form>
$(w.document).html(w.opener.runonload());
You can't set innerHTML—or, consequently, jQuery's html()—on a Document object itself.
Even if you could, you wouldn't be able to do it using html(), because that parses the given markup in the context of an element (usually <div>) from the current document. The doctype declaration won't fit/work, putting <html>/<body>/etc inside a <div> is invalid, and trying to insert the elements it creates from the current ownerDocument into a different document should give a WRONG_DOCUMENT_ERR DOMException. (Some browsers let you get away with that bit though.)
This is a case where the old-school way is still the best:
w= window.open('', '_blank');
w.document.write($('#newcode').val());
w.document.close();
Whilst you can inject innerHTML into a pop-up's document.documentElement, if you do it that way you don't get the chance to set a <!DOCTYPE>, which means the page is stuck in nasty old Quirks Mode.

Write elements into a child iframe using Javascript or jQuery

I have something like this:
<!doctype html>
<html>
<body>
<iframe id="someFrame"></iframe>
</body>
</html>
And I would like to use jQuery to write elements such that the full equivalent HTML would be like this:
<!doctype html>
<html>
<body>
<iframe id="someFrame">
<!-- inside the iframe's content -->
<!-- <html><body> -->
<div>A</div>
<div>B</div>
<div>C</div>
<!-- </body></html> -->
</iframe>
</body>
</html>
Alternatively, any plain-old-Javascript would be fine.
Thanks.
Edit: After a little more research, it seems I am looking for an IE-equivalent of the contentDocument property of an iframe. "contentDocument" is a W3C standard which FF supports, but IE does not. (surprise surprise)
You can do both, you just have to target differently:
var ifrm = document.getElementById('myIframe');
ifrm = ifrm.contentWindow || ifrm.contentDocument.document || ifrm.contentDocument;
ifrm.document.open();
ifrm.document.write('Hello World!');
ifrm.document.close();
After some research, and a corroborating answer from Mike, I've found this is a solution:
var d = $("#someFrame")[0].contentWindow.document; // contentWindow works in IE7 and FF
d.open(); d.close(); // must open and close document object to start using it!
// now start doing normal jQuery:
$("body", d).append("<div>A</div><div>B</div><div>C</div>");
There are two reliable methods to access the document element inside an iframe:
1. The window.frames property:
var iframeDocument = window.frames['iframeName'].document; // or // var iframeDocument = window.frames[iframeIndex].document;
Demo
2. The contentDocument property:
var iframeDocument = document.getElementById('iframeID').contentDocument; // or // var iframeDocument = document.getElementById('iframeID').contentWindow.document;
Demo
I am going out on a limb here and suggest that the answers proposed so far are not possible.
If this iframe actually has a src="somepage.html" (which you ought to have indicated, and if not, what is the point of using iframe?), then I do not think Jquery can directly manipulate html across frames in all browsers. Based on my experience with this kind of thing, the containing page cannot directly call functions from or make any sort of Javascript contact with the iframe page.
Your "somepage.html" (the page that loads in the iframe) needs to do two things:
Pass some kind of object to the containing page that can be used as a bridge
Have a function to set the HTML as you desired
So for example, somepage.html might look like this:
<!doctype html>
<html>
<head>
<script src="jquery.js">
</script>
<script language=JavaScript>
<!--//
var bridge={
setHtml:function(htm) {
document.body.innerHTML=htm;
}
}
$(function() { parent.setBridge(bridge); });
//--></script>
</head>
<body></body>
</html>
and the containing page might look like this:
<!doctype html>
<html>
<head>
<script src="jquery.js">
</script>
<script language=JavaScript>
<!--//
var bridge;
var setBridge=function(br) {
bridge=br;
bridge.setHtml("<div>A</div><div>B</div><div>C</div>");
}
//-->
</script>
</head>
<body><iframe src="somepage.html"></iframe></body>
</html>
This may appear a bit convoluted but it can be adapted in a number of directions and should work in at least IE, FF, Chrome, and probably Safari and Opera...
I have found this to be cross-browser compatible... a little crossing of previous answers and a bit of trial & error of my own. :)
I'm using this for a download of a report, or, if an error (message) occurs, it's displayed in the iFrame. Most of the users will probably have the iFrame hidden, I'm using it multi-functional.
The thing is I have to clear the contents of the iFrame every time I click the report download button - the user can change parameters and it happens there are no results which then is displayed in the iFrame as a message. If there are results, the iFrame remains empty - because the code below has cleared it and the window.open(...) method generates a Content-Disposition: attachment;filename=... document.
var $frm = $("#reportIFrame");
var $doc = $frm[0].contentWindow ? $frm[0].contentWindow.document : $frm[0].contentDocument;
var $body = $($doc.body);
$body.html(''); // clear iFrame contents <- I'm using this...
$body.append('<i>Writing into the iFrame...</i>'); // use this to write something into the iFrame
window.open(Module.PATH + 'php/getReport.php' + Report.queryData, 'reportIFrame');
I do not have a browser that supports contentDocument but I've coded it this way so I'm leaving it. Maybe someone has older browsers and can post compatibility confirmation/issues?

Categories

Resources