简体   繁体   中英

How to write into chrome/ie/ff f12 console from c# asp.net application code behind

如何从 ASP.NET Web 应用程序的代码隐藏中重现 JavaScript 的 console.log() 功能?

令人惊讶的是,这之前没有给出,但这在 Chromes 控制台的代码隐藏中对我有用:

Response.Write("<script>console.log('opened window');</script>")

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.

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>");
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM