Created
May 26, 2011 22:17
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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); | |
} | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Awesome, works like a charm thanks!