-1

Follow the following steps.

Steps 1:

  1. Go to google.
  2. Open the javascript console.
  3. Enter the command: document.all.q.value = "hello"

As expected the element with a name of "q" (the search field) is set to "hello"). See image

Steps 2:

  1. Go to google.
  2. In the address bar type javascript: document.all.q.value = "hello!"
  3. Press Enter

If your browser is either Internet Explorer, or Google Chrome, the javascript will have replaced the google website with an entirely blank page, with the exception of the word "Hello".

Lazy? Here's an image.

Finally

Now that you've bugged out your browser, go back to Google.com and repeat Steps 1. You should receive an error message "Uncaught ReferenceError: document is not defined (...) VM83:1 See image

Question:

Am I doing something wrong? And is there another method which works, while still using the address bar for JS input?

Sancarn
  • 2,575
  • 20
  • 45

2 Answers2

1

The purpose of a javascript: scheme URL is to generate a new page using JavaScript. Modifying the existing page with it is something of a hack.

document.all.q.value = "hello!"; evalues as "hello!", so when you visit that URL, a new HTML document consisting solely of the text hello! is generated and loaded in place of the existing page.

To avoid this: Make sure the JS does not return a string. You can do this by using void.

javascript:void(document.all.q.value = "hello!");
Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
  • I see! Thanks for all the info! And indeed that does work fine now! Also, never knew about void() function. Thanks a bunch! – Sancarn Sep 04 '16 at 20:54
-1

When messing around with javascript: in the adressbar some (if not the most) browsers handle it as a new page, so you have to add a window.history.back(); at the end

javascript: document.all.q.value = "hello!"; window.history.back();
Dimitri L.
  • 4,499
  • 1
  • 15
  • 19
  • I did try that, weird thing happened. First the text got inputted then it instantly got removed :P Anyway, Quentin's solution works out perfectly! Thanks for yours though :) – Sancarn Sep 04 '16 at 20:59