6

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

3
  • 2
    You just want logging capabilities? Glimpse 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. Commented Jan 29, 2016 at 20:34
  • Idk what glimpse is but I would assume a framework could do something as simple as this. Commented Jan 29, 2016 at 20:35
  • Sure, it can. Why don't you try doing it? And I linked to Glimpse in my previous comment. Commented Jan 29, 2016 at 20:35

3 Answers 3

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>")
Sign up to request clarification or add additional context in comments.

1 Comment

In my case, this prints out "<script>console.log('opened window');</script>". So just let away the js-commands and it's fine
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>

Alternatively, you could use Glimpse as suggested in the comments under the question.

4 Comments

can you explain how this works? What does that string do?
I don't think the @() syntax is going to work in Web Forms. That's for Razor. You would need to use <% %> style syntax.
Assumed he was using razor. That's trivial and doesn't change the overall answer, just syntax.
"You're not going to directly be able to write to the browser's console via code behind" Which is a real shame, because Web Forms makes it extremely simple to write to the web page via code behind, thanks to runat="server".
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>");
}

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.