henry
henry

Reputation: 1718

How to capture visibility change / app background event in js for a win8 metro app

I asked this question about how to capture visibility changes in a metro app: How to tell if JS Windows8 metro app is visible or not

And it seems like there two answers: 1) checkpoint will be called about 10 seconds after the app loses focuses because the app will be suspended

2) the page visibility events will work.

However, when I do the following in my default.js I don't see either of these things happening:

var onVisibilityChange = function (args) {
  console.log("Visibility changed. (this will never appear");
};
app.addEventListener("visibilitychange", onVisibilityChange);

// ...

app.oncheckpoint = function (args) {
  console.log("APP onCheckpoint (this also never appears");
};

Does anybody have an example of capturing when the app starts/stops being visible that works?

Upvotes: 0

Views: 5869

Answers (3)

Dr. Lemon Tea
Dr. Lemon Tea

Reputation: 649

I recommend to use this library: http://dueljs.studentivan.ru/

Upvotes: 0

Dominic Hopton
Dominic Hopton

Reputation: 7292

For visibility, you need to use the document:

document.addEventListener("visibilitychange", function() {
    console.log("Visible: " + !document.hidden);
})

For Checkpoint, your code is correct but note:

  • Suspend/Resume does not happen automatically with the debugger attached. You need to use the toolbar in Visual studio for controlling the suspend state.
  • Your console.log won't show up till the app is resumed (unclear why, probably some cache), hower you can verify it's executed before being suspended by setting a breakpoint on that line, and using the VS toolbar button

Upvotes: 6

henry
henry

Reputation: 1718

One solution is:

var onVisibilityChange = function (args) {
  var state = document["visibilityState"];
  if (state == "visible")
  {
    console.log("COMING IN");
  }
  else if (state == "hidden") {
    console.log("AWAY");
  }
};
document.addEventListener("visibilitychange", onVisibilityChange, false);

Upvotes: 0

Related Questions