I'm writing an extension for browser using Javascript. How do I get the whole HTML source code and re-write that?
I need to change some words inside that source and reopen that page.
I'm writing an extension for browser using Javascript. How do I get the whole HTML source code and re-write that?
I need to change some words inside that source and reopen that page.
In javascript you could try something like:
var source = document.documentElement.outerHTML;
...and to get the doctype use:
var doctype = document.doctype;
source: Get the whole document's html with JavaScript/JQuery
I also found this post regarding doing the same thing in a Chrome extension if this helps:
Getting the source HTML of the current page from chrome extension
Try something like this to get the page source:
document.documentElement.innerHTML
And this to change it:
document.documentElement.innerHTML = '<body>I like pie</body>'
document.documentElement
is the <html> ... </html>
element on the page, and innerHTML
will give is the HTML of it.
You can get the source of the whole page with:
oldSource = document.getElementsByTagName("html")[0].innerHTML;
And then replace the entire page with:
document.write(newSource);
Or, if you want to replace few elements on the page, use one of the following:
If you know the id
of the element:
oldText = document.getElementById("idOfElement").innerHTML;
document.getElementById("idOfElement").innerHTML = newText;
If you know the class
of the element:
oldText = document.getElementsByTagName("classOfElement")[0].innerHTML;
document.getElementsByTagName("classOfElement")[0].innerHTML = newText;
(where 0
means you're looking for the first element with the specificed classname on the page)
If you know the tag name of the element:
oldText = document.getElementsByClassName("tagName")[0].innerHTML;
document.getElementsByClassName("tagName")[0].innerHTML = newText;
(where 0
means you're looking for the first element with the specificed tag name on the page)
Or, you can use jQuery selectors, for example:
oldText = $("#idOfElement").html();
oldText = $(".classOfElement").html();
oldText = $("tagName:nth-child(1)").html();
$("#idOfElement").html(newText);
$(".classOfElement").html(newText);
$("tagName:nth-child(1)").html(newText);
Where :nth-child(1)
means you're looking for the first element with the specificed tag name on the page. You can also use this when searching for classes, if there are multiple element with the same classname.