views:

87

answers:

4

I'm trying to create my own bookmarklet, and there aren't exactly a huge number of guides for doing so. Basically, right now I'm trying to figure out why I can't just do javascript:document.write("HAI, WORLD"), which has the unintended effect of replacing the window contents.

It's my understanding from elsewhere that Javascript replaces the entire contents of the window with the return value of a method, so I've also tried javascript:void(document.write("wut")), but the entire window contents are still replaced.

+6  A: 

That's because the page is already loaded and it doesn't know where you want to write to. Use document.documentElement.appendChild(document.createTextNode("HAI, WORLD")).

Eli Grey
You should use `document.body` instead since appending extra elements to `<html>` is technically invalid.
Casey Hope
There's no guarantee that the body has loaded whenever he runs his script. Also, if it *was* invalid to add nodes to the root node, I'd get a `DOMException.HIERARCHY_REQUEST_ERR` error.
Eli Grey
A: 

I try to understand your "question", but I think you'd want to let it open up in a new window, right?

Then you'd need to use: javascript:window.open("<url to website>", "some title");

Pindatjuh
No, I wouldn't.
Tyler Menezes
A: 

If document.write() is called after the page has finished loading, the entire contents of the page will be overwritten. This is the intended effect of the function.

If you wish to modify the HTML code on the fly, you have a few options:

  • document.getElementById("foobar").innerHTML("baz")
  • document.getElementById("foobar").appendChild(document.createTextNode("baz"))

Additionally, you should look into a framework like jQuery, which can handle a lot of this for you:

  • $("#foobar").html("baz")
carl
Personally, for bookmarklets, I'd prefer not to use any third party frameworks and wrap my javascript in `(function(){})()` to avoid potential conflict with scripts already on the page. This is where learning pure javascript comes in handy.
slebetman
A: 

yeah as Elijah said, or if you want to alter the browser's status bar:

window.status = 'my new status'
jspcal
Note too, I think Firefox disables this ability by default.
alex
in firefox you can set disable_window_status_change to false
jspcal