how to run code when Microsoft toast notification button is pressed in javascript

1.1k Views Asked by At

I am trying to make a microsoft toast notification that has buttons or so called "actions" in this code i have 3 buttons A,B,C and i want to check if any of them are clicked and if so the run a line of code just for example if A is clicked then run debug.log('A') how can i do that? (im new to visual studio and javascript)

document.addEventListener('keydown', logKey);

function logKey(e) {
    var notifLib = Microsoft.Toolkit.Uwp.Notifications;

    var toastContent = new notifLib.ToastContent();
    var toastVisual = new notifLib.ToastVisual();
    var toastBindingGeneric = new notifLib.ToastBindingGeneric();

    var adaptiveText = new notifLib.AdaptiveText();
    adaptiveText.text = "Hello World";
    toastBindingGeneric.children.push(adaptiveText);

    adaptiveText = new notifLib.AdaptiveText();
    adaptiveText.text = "This is a simple toast message";
    toastBindingGeneric.children.push(adaptiveText);

    toastVisual.bindingGeneric = toastBindingGeneric;

    toastContent.visual = toastVisual;

    var toastActionsCustom = new notifLib.ToastActionsCustom();

    var toastButton = new notifLib.ToastButton("a", "action=at&userId=1");
    toastButton.activationType = notifLib.ToastActivationType.background;
    toastActionsCustom.buttons.push(toastButton);

    toastButton = new notifLib.ToastButton("b", "action=b&userId=1");
    toastButton.activationType = notifLib.ToastActivationType.background;
    toastActionsCustom.buttons.push(toastButton);

    toastButton = new notifLib.ToastButton("c", "action=b&userId=1");
    toastButton.activationType = notifLib.ToastActivationType.background;
    toastActionsCustom.buttons.push(toastButton);

    toastContent.actions = toastActionsCustom;

    // Create the toast notification
    var toastNotif = new Windows.UI.Notifications.ToastNotification(toastContent.getXml());

    // And send the notification
    Windows.UI.Notifications.ToastNotificationManager.createToastNotifier().show(toastNotif);
};
1

There are 1 best solutions below

9
Richard Zhang On

for UWP applications, when the notification button is pressed, the activated event of the application will be triggered. In javascript, it can be written like this:

Windows.UI.WebUI.WebUIApplication.addEventListener("activated", function (activatedEventArgs) {
     if (activatedEventArgs.kind == Windows.ApplicationModel.Activation.ActivationKind.toastNotification) {
          console.log(activatedEventArgs.argument);
     }
});

If you are using WinJs to build your application, you can find the corresponding code block that handles the click of the Toast notification in the app.onactivated event in main.js

...
else if (args.detail.kind === activation.ActivationKind.launch) {
    if (args.detail.arguments) {
    }
    ...
}
...