Execute JavaScript functions in google chrome address bar

Viewed 4890

I want to execute JavaScript code in address bar of my google chrome javascript:. It works fine with something simple such as:

javascript:alert("aaa");

But it doesn't work with more than one alert. I found out that placing everything in brackets would do the trick:

javascript:{alert("aaa"); alert("blabla"); document.getElementsById("myId").innerHTML = "aa";}

But it doesn't work with something more complex such as for or calling a function. I really need to execute for like this:

var elements = document.getElementsByTagName('div');

for (var i = 0; i < elements.length; i++) {
    elements[i].innerHTML = "foo";
}​

I tried it with both javascript: and javascript:{...} and it didn't work.

So my question is: How can I execute more complex JavaScript code such as this one above?

3 Answers

You can warp everything inside an immediately-invoked Function Expressions (IIFE):

javascript:(function(){
var elements = document.getElementsByTagName('div');

for (var i = 0; i < elements.length; i++) {
    elements[i].innerHTML = "foo";
}​})()

I kept the newlines to make the code clearer. you might need to write everything in a single line.

Related