6

How can I reproduce JavaScript's console.log() functionality from code-behind in ASP.NET web application?

TylerH
  • 20,799
  • 66
  • 75
  • 101
codemonkeyliketab
  • 320
  • 1
  • 2
  • 17
  • 2
    You just want logging capabilities? [Glimpse](http://getglimpse.com/) seems more appropriate. But if you really want to do this, why not just have it embed `console.log` statements in the output? Seems like it'd be fairly trivial. – mason Jan 29 '16 at 20:34
  • Idk what glimpse is but I would assume a framework could do something as simple as this. – codemonkeyliketab Jan 29 '16 at 20:35
  • Sure, it can. Why don't you try doing it? And I linked to Glimpse in my previous comment. – mason Jan 29 '16 at 20:35

3 Answers3

15

Surprised this hasn't been given before but this works for me in Code Behind with Chromes console:

Response.Write("<script>console.log('opened window');</script>")
Joel
  • 151
  • 1
  • 2
  • 1
    In my case, this prints out "". So just let away the js-commands and it's fine – Pablo Jul 12 '18 at 13:32
9

You're not going to directly be able to write to the browser's console via code behind. Code behind is being executed on your server, and the browser (or consumer) has no idea what is going on there.

If you want to pass messages from your code-behind that will show in the console.log, you'll have to render them into your page to be executed by javascript.

For instance:

<script>
console.log('@(Model.your_message)');
</script>

Hope this helps

Edit: Plus 1 for the Glimpse suggestion in the comments above.

ohiodoug
  • 1,493
  • 1
  • 9
  • 12
1

Building on @Joel's answer (I don't have comment rights yet) ... it works for me in Chrome, and I built this simple extension method to make it easier & available for all my code-behind pages:

public static void ConsoleLog(this Page page, string msg)
{
    msg = msg.Replace("'", ""); //Prevent js parsing errors. Could also add in an escape character instead if you really want the 's.
    page.Response.Write("<script>console.log('"+msg+"');</script>");
}
HaileyStorm
  • 33
  • 1
  • 7