如何在不使用 WinjS 库的情况下在通用 Windows 应用程序中添加后退按钮事件?

How to add back button event in Universal Windows App without using WinjS Library?

这是我的main.js

(function () {
"use strict";

//No need of WinJS
var activation = Windows.ApplicationModel.Activation;
var roaming = Windows.Storage.ApplicationData.current.roamingSettings;

// For App Start Up
Windows.UI.WebUI.WebUIApplication.addEventListener("activated", function (args) {
    if (args.detail[0].kind === activation.ActivationKind.launch) {
        if (roaming.values["currentUri"]) {
            if (roaming.values["UserName"])
            {
                localStorage.setItem("UserName", roaming.values["UserName"]);
                window.location.href = roaming.values["currentUri"];
            }
        }
    }
});

// For App Suspension
Windows.UI.WebUI.WebUIApplication.addEventListener("suspending", function (args) {
    roaming.values["currentUri"] = window.location.href;
    roaming.values["UserName"] = localStorage.getItem("UserName");
});

// For Resuming App
Windows.UI.WebUI.WebUIApplication.addEventListener("resuming", function (args) {
    var roam = Windows.Storage.ApplicationData.current.roamingSettings;
    if (roam) {
        if (roam.values["currentUri"]) {
            localStorage.setItem("UserName", roam.values["UserName"]);
            window.location.href = roam.values["currentUri"];
        }
    }
}, false);
// not working backpressed event
Windows.UI.WebUI.WebUIApplication.addEventListener("backpressed", function (args) {
   // to do
}, false);})();

我需要在不使用 winjs 库的情况下为 windows phone 添加返回按键事件? 有人可以推荐我吗?

我在我的应用程序中使用 ms-appx-web 上下文。我不想使用 winjs 库。

I need to add back key press event for windows phone without using winjs library?

backpressed 事件应附加到 Windows.Phone.UI.Input.HardwareButtons 而不是 Windows.UI.WebUI.WebUIApplication

如果你参考HardwareButtons.BackPressed and HardwareButtons,你会发现backpressed事件是这样使用的:

var hardwareButtons = Windows.Phone.UI.Input.HardwareButtons;
function onBackPressed(eventArgs) { /* Your code */ }

// addEventListener syntax
hardwareButtons.addEventListener("backpressed", onBackPressed);
hardwareButtons.removeEventListener("backpressed", onBackPressed);

并且由于您不是在制作单页应用程序。此事件应附加在每个新页面的 JS 代码上。

更新: 如果您想以编程方式了解当前设备,可以使用以下 if 语句:

if (deviceInfo.operatingSystem.toLowerCase() == "windowsphone")
{
     //do your windows phone logic
} else if (deviceInfo.operatingSystem.toLowerCase() == "windows")
{
     //do your windows logic
}

我用过这个-

var flag = Windows.Foundation.Metadata.ApiInformation.isTypePresent("Windows.Phone.UI.Input.HardwareButtons");

    if (flag) {
        var hardwareButtons = Windows.Phone.UI.Input.HardwareButtons;
        hardwareButtons.addEventListener("backpressed", onBackPressed);
    }

对我来说效果很好!