How can I reproduce JavaScript's console.log() functionality from code-behind in ASP.NET web application?
3 Answers
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>")
1 Comment
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>
Alternatively, you could use Glimpse as suggested in the comments under the question.
4 Comments
@() syntax is going to work in Web Forms. That's for Razor. You would need to use <% %> style syntax.runat="server".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>");
}
console.logstatements in the output? Seems like it'd be fairly trivial.