Carl Patenaude Poulin Carl Patenaude Poulin - 3 months ago 8x
Javascript Question

How can I see if my JavaScript-based UWP is running in a "background task" context?

If I write

var taskInstance = Windows.UI.WebUI.WebUIBackgroundTaskInstance.current;

and I execute my app normally, I get an "access denied" exception. What is the best practice to detect that I am indeed running as a background task?


UWP "background tasks" are implemented as web workers. Detecting web worker context is covered in some other SO questions (1, 2). One solution is the following:

function inBackgroundTaskContext() {
    return typeof importScripts === 'function'

importScripts is a function that is callable from within background tasks. It is not defined when the app is running within a "normal" app context.