How to create hyperlinks linked to javascript functions in Chrome's console.log?

bigp picture bigp · Apr 16, 2015 · Viewed 16k times · Source

I'm trying to write entries to the console that would contain links to trigger javascript functions upon clicking on them:

console.log("javascript:alert('Hello World');");
console.log("<a href=\"javascript:alert('Hello World');\"/>test</a>");
console.log("[DisplayObject 'Hello World' <a href=\"javascript:alert('Hello World');\">reveal</a>]");

All these attempts fail.

screenshot

Is there any way to print it similarly to an "http://..." link, like so...

example

... only, have the text linked to a javascript statement or function instead?

The reason I'm doing this is to be able to quickly reveal which items on the screen are tied to a specific log entry (example: Making a CreateJS sprite scale-up when the log entry is clicked on).

Answer

Marco Bonelli picture Marco Bonelli · Apr 16, 2015

The Google Chrome console, like many other browser's developer tools consoles, automatically parses any URL into a link to that exact page. This is the only way of obtaining such URLs, and, unfortunately, you cannot actually log "custom URLs".

This means that the following logs will be turned into a clickable link automatically:

console.log('http://example.com');
console.log('www.example.com');
console.log('ftp://mysite.com');
console.log('chrome://history')
console.log('chrome-extension://abcdefg...');

but, on the contrary, the following ones won't:

console.log('example.com');
console.log('<a href="http://www.example.com">Link</a>');
console.log('javascript:doSomething(someValue);');