2

I would like to send some parameters to my desktop notification but i can't retrieve them.

I open a notification with that code :

var notification = webkitNotifications.createHTMLNotification(
  '../html/notification.html?data='+nb
);

Where nb is my variable.

notification.html :

<!DOCTYPE html>
<html>
<head>
<title>Notification</title>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script type="text/javascript" src="../js/notification.js"></script>
</head>
<body>
    <div id="message">Vous avez <span></span></div>
</body>
</html>

notification.js :

function getUrlVars() {
    var vars = [], hash;
    var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
    for (var i = 0; i < hashes.length; i++) {
        hash = hashes[i].split('=');
        vars.push(hash[0]);
        vars[hash[0]] = hash[1];
    }
    return vars;
}
var first = getUrlVars()['data'];

$('#message span').html(first +' nouveau message');

The result is "Vous avez" instead of "Vous avez 1 nouveau message" for example.

I checked if my notification.js is loaded. How to check the value of "first"? How to debug that JS code? Or have you a better method to retrieve GET parameters in URL?

Thank's a lot.

Regards

Syl
  • 2,232
  • 8
  • 34
  • 45

1 Answers1

4

The Query String is not setup to be parsed easily with JS. Do you only need to pass one String?

If so, use the Hash instead of the Query String:

var notification = webkitNotifications.createHTMLNotification('../html/notification.html#' + nb);

Then in notification.js:

$('#message span').html(window.location.hash.substr(1) + ' nouveau message');

If you need to pass more than one variable, you can use a Stringified JSON object:

var data = {
        var1: "somedata",
        var2: 12345
    },    
    notification = webkitNotifications.createHTMLNotification('../html/notification.html#' + JSON.stringify(data));

Then in notification.js:

var data = JSON.parse(window.location.hash.substr(1));
$('#message span').html('var1 is ' + data.var1 + ' var2 is' + data.var2);

If you get parse errors you may have to use encodeURIComponenet() and decodeURIComponent()

Ansel Santosa
  • 8,224
  • 1
  • 28
  • 39