Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

desktop notification using javascript in windows form

i am new to this and i am creating simple application in which i click a button and a notification on desktop should be displayed. i am doing this in windows form c#

the error is " NullReferenceException was unhandled

i have one button Notify in form1. i have tried this:

form1.cs

     public Form1()
            {
                InitializeComponent();
                this.Load += new EventHandler(Form1_Load);
                webBrowser1.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(webBrowser1_DocumentCompleted);
                webBrowser1.ScriptErrorsSuppressed = true;
            }

            private void btnNotify_Click(object sender, EventArgs e)
            {
                webBrowser1.Document.InvokeScript("notifyMe");
            } 

 private void Form1_Load(object sender, EventArgs e)
        {
            string CurrentDirectory = Directory.GetCurrentDirectory();
            webBrowser1.Navigate(Path.Combine(CurrentDirectory,"HTMLPage1.html"));
        }

        private void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
        {
            webBrowser1.ObjectForScripting = this;

code for HTMLPage1.html :

<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta charset="utf-8" />
    <title></title>
    <script language="javascript" type="text/javascript">
    document.addEventListener('DOMContentLoaded', function () {
    if (Notification.permission !== "granted")
    Notification.requestPermission();
    });

    function notifyMe() {
    if (!Notification) {
    alert('Desktop notifications not available in your browser. Try Chromium.');
    return;
    }

    if (Notification.permission !== "granted")
    Notification.requestPermission();
    else {
    var notification = new Notification('Notification title', {
    icon: 'http://cdn.sstatic.net/stackexchange/img/logos/so/so-icon.png',
    body: "Hey there! You've been notified!",
    });

    notification.onclick = function () {
    window.open("http://stackoverflow.com/a/13328397/1269037");
    };

    }

    }
    </script>
</head>
<body>

</body>
</html>

even if i simply put alert("Hi") in notifyMe() function, nothing else. still it displays the same error.

ErrorMsg

like image 510
Dinav Ahire Avatar asked Jun 20 '15 05:06

Dinav Ahire


1 Answers

I have tried your code.. you should use

document.attachEvent('DOMContentLoaded', function () {..

Instead of

document.addEventListener("..

That worked from here...read more about it here https://stackoverflow.com/a/1695383/4155741

you should also remove that comma at the end of .. body: "Hey there! You've been notified!", as it prevent the script from be compiled.

like image 63
konzo Avatar answered Oct 13 '22 03:10

konzo