Office Add-ins (Apps for Office) and window.alert()

What! So, you are getting started writing an Apps for Office or Office add-in as they are now known, and you need to display a JavaScript alert. Maybe you are doing this because you need to prompt the user with some information, or maybe you are doing this because you need to test something. So you enter your code:

window.alert("Hello world!");

When you run it, nothing happens.

This is because JavaScript allows you to redefine anything. And the Office team redefined certain window functions because they felt they were intrusive and because they do not work the same (or at all) on some platforms. So the suggestion is to not use them. The proper way to do this is to use the app.ShowNotifification command:

app.showNotification(title, text)

However, if you are like me and use them to help you debug/code/proof things, you might really need them. I found that if you add the following to your Office.initialize method, they will work:

// The initialize function must be run each time a new page is loaded
Office.initialize = function (reason) {
    $(document).ready(function () {

        delete window.alert;       // assures alert works
        delete window.confirm;     // assures confirm works
        delete window.prompt;      // assures prompt works
        /* the rest of your code here */

4 thoughts on “Office Add-ins (Apps for Office) and window.alert()

  1. When I used app.showNotification(title, text); it is giving me error that app is undefined. Can you guide me about its class/js I need to include in my project?

    • This was an older function used in templates built by Office a long time ago and gone now. It was just an added function with a respective HTML div in the template. Essentially, you will need to add a DIV on your taskpane then define the function to have it modify the div and display your message.

Leave a Reply