0

I am trying to add this line to the url bar of the browser (my browser is Chrome)

javascript:document.getElementsByTagName("head")[0].innerHTML+="<link rel='stylesheet' type='text/css' href='st1.css'>";

When I press enter, the whole page disappears.

When I check the source code, I can see that the JavaScript was executed, but, the whole content disappears, though the content of the body stays the same in the source code !

Why is that happening?

6
  • 1
    Maybe the style sheet you're embedding has a rule that is hiding the body? Commented Dec 22, 2012 at 12:21
  • Use the devtools' DOM inspector and tell us what you see. Commented Dec 22, 2012 at 12:25
  • This works for me: javascript:(function (){}(document.getElementsByTagName("head")[0].innerHTML+="<link rel='stylesheet' type='text/css' href='st1.css'>")); Commented Dec 22, 2012 at 12:32
  • the new css file contains only a rule to change <td> background style ONLY, and has no rule that modify the body the DOM inspector shows the following : <link rel='stylesheet' type='text/css' href='st1.css'> => added in the head section and the body remains the SAME .. and every thing inside of it is the same, all the content .. Commented Dec 22, 2012 at 12:35
  • Panav Kapoor , your answer really worked .. thank you .. if you put it in a separate answer .. i'd rate it for you :) Commented Dec 22, 2012 at 12:37

3 Answers 3

1

The JavaScript you have written returns document.getElementsByTagName("head")[0]

To make sure that there is no return value, change the code to something like this :

javascript:(function(){document.getElementsByTagName("head")[0].innerHTML+="<link rel='stylesheet' type='text/css' href='st1.css'>";}());
Sign up to request clarification or add additional context in comments.

Comments

0

I guess innerHTML is only for displaying it in the webpage and not for adding anything in the headers.

Precisely you can't use that to do anything in the section.

2 Comments

Are you guessing or do you know it?
innerHTML has done the task .. and added the css link successfully
0

You must make sure the statement doesn't return anything — anything that is deemed to be returnable in the expression will be taken as a URL or page content to replace the current page. Te expression += will by default. A good solution is to precede the statement with void such that nothing is returned.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.