I would like to rewrite the <html>
content using Greasemonkey.
I tried this:
document.open()
document.write(html)
document.close()
Not working.
document.body.innerHTML = html
only replaces the content.
Some suggestions?
I would like to rewrite the <html>
content using Greasemonkey.
I tried this:
document.open()
document.write(html)
document.close()
Not working.
document.body.innerHTML = html
only replaces the content.
Some suggestions?
Don't use document.write()
. It has all kinds of security restrictions (due to abuse by bad guys) and is fraught with pitfalls.
if you try to use it, as in your question, in a userscript; Firefox will typically either stall the page completely or go into a perpetual Connecting...
then reload cycle -- depending on when your script fires and whether you use unsafeWindow.stop()
.
This kind of code still works in Chrome (for now), but remains a bad practice. Not sure about other browsers.
The correct approach is to use DOM methods. For example:
var D = document;
var newDoc = D.implementation.createHTMLDocument ("My new page title");
window.content = newDoc;
D.replaceChild (
D.importNode (newDoc.documentElement, true),
D.documentElement
);
D.body.innerHTML = '<h1>Standby...</h1>';
For enhanced performance, you may also wish to use:
// @run-at document-start
// @grant unsafeWindow
and then place an unsafeWindow.stop ();
at the top of the userscript code.
Re: "How do I rewrite the head content with this solution?"
:
This example already rewrites the <head>
. The new head will be:
<head><title>My new page title</title></head>
in this case.
To add additional head elements, use DOM code like:
var newNode = D.createElement ('base');
newNode.href = "http://www.example.com/dir1/page.html";
var targ = D.getElementsByTagName ('head')[0];
targ.appendChild (newNode);
Except:
GM_addStyle()
to easily create <style>
nodes.<script>
nodes is almost always pointless in your scenario. Just have your userscript do any needed JS processing.<meta>
will be added but not processed (especially in Firefox). Depending on the parameters, these are only parsed on initial load from a server.
Standby...
';`. – Tomáš Zato Oct 09 '16 at 09:00