Skip to content

Instantly share code, notes, and snippets.

@yoeun
Created May 26, 2011 22:17
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yoeun/994228 to your computer and use it in GitHub Desktop.
Save yoeun/994228 to your computer and use it in GitHub Desktop.
Write to browser Javascript console from Silverlight in most browsers. Works with code outside of UI thread.
// Credit: Kodierer http://bit.ly/pqcSq
using System;
using System.Threading;
using System.Windows;
using System.Windows.Browser;
using System.Windows.Threading;
public class Log
{
public static Write(object message, params object[] values)
{
HtmlWindow window = HtmlPage.Window;
var isConsoleAvailable = (bool)window.Eval("typeof(console) != 'undefined' && typeof(console.log) != 'undefined'");
if (isConsoleAvailable)
{
var createLogFunction = (bool)window.Eval("typeof(sllog) == 'undefined'");
if (createLogFunction)
{
// Load the logging function into global scope:
string logFunction = "function sllog(msg) { console.log(msg); }";
string code = string.Format(@"if(window.execScript) {{ window.execScript('{0}'); }} else {{ eval.call(null, '{0}'); }}", logFunction);
window.Eval(code);
}
// Prepare the message
DateTime dateTime = DateTime.Now;
string output = string.Format("{0} - {1}", dateTime.ToString("u"), string.Format(message.ToString(), values));
// Invoke the logging function:
var logger = window.Eval("sllog") as ScriptObject;
if (logger != null)
{
// Workaround: Cannot call InvokeSelf outside of UI thread, without dispatcher
Dispatcher d = Deployment.Current.Dispatcher;
if (!d.CheckAccess())
{
d.BeginInvoke((ThreadStart) (() => logger.InvokeSelf(output)));
}
else
{
logger.InvokeSelf(output);
}
}
}
}
}
@kyriakosio
Copy link

Awesome, works like a charm thanks!

@mdacar
Copy link

mdacar commented Jan 9, 2015

This is a live saver. Thank you!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment