HTML5 Desktop notifications - html

I am dealing with desktop notifications on HTML5. My problem is on Firefox (on Chrome is fine), there I cann't throw more than 1 notification.
//Requestion permissions blablabla
if (permission === "granted") {
var notification = new Notification(id, opt, null);
var notification2 = new Notification(id, opt, null);
var notification3 = new Notification(id, opt, null);
}
This doesn't work on Firefox, if I comment the last ones, works.
Somebody know if I can do this

Many aspects of displaying notifications are up to browsers, but in particular in this case you need to show more then one notification at the same time you can set a different "tag" attribute to each notification (http://www.w3.org/TR/notifications/#tags-example). If you don't specify a tag, the default one is used and the last notification "wins" over the previous ones.
Check this example:
<button id="authorize">Authorize notification</button>
<button id="show">Show notification</button>
<button id="show_another">Show another notification</button>
<script>
function authorizeNotification() {
Notification.requestPermission(function(perm) {
alert(perm);
});
}
function showNotification(myTag) {
var notification = new Notification("This is a title with tag " + myTag, {
dir: "auto",
lang: "",
body: "This is a notification body with tag " + myTag,
tag: myTag,
});
}
document.querySelector("#authorize").onclick = authorizeNotification;
document.querySelector("#show").onclick = function(){ showNotification("firstTag"); };
document.querySelector("#show_another").onclick = function(){ showNotification("secondTag"); };
</script>
If you click "show notification" many times, the notification is closed and a new one is opened. Using the second button a new notification is shown without closing the old one.
You can find a working sample at JSFiddle (http://jsfiddle.net/TuJHx/350/)

Related

Notifications With Tags Don't Show On Chrome

I'm trying to send notifications with a tag.
When I send two notifications with the same tag, I expect the second notification to replace the first one if it's still visible, or to just show up if the first one auto-hided. However, when testing on Chrome, the second notification doesn't show up at all if the first one is already hidden. I have no problems when testing on Firefox.
How can I make this work for Chrome?
Here's my sw.js:
self.addEventListener('push', function (event) {
const data = event.data.json();
let notificationData = {
body: data.body,
tag: data.tag
};
console.log('got notification', data, notificationData);
let promise = self.registration.showNotification(data.title, notificationData);
event.waitUntil(promise);
});

how to toggle appended elements using multiple buttons and pass info to the output JQuery

I have asked kind of a similar question before : how to toggle using multiple buttons and pass info to the output JQuery
It was answered well, but this time I am using a different approach in the code thus a new question.
I am trying to toggle info and append a div using three different buttons.
Here is The code https://jsfiddle.net/YulePale/nruew82j/40/
JavaScript
document.getElementById("brazil").addEventListener('click', function(e){
if(e.currentTarget.dataset.triggered) return;
e.currentTarget.dataset.triggered = true;
AppendFunction();
function AppendFunction() {
var para = document.createElement("p");
var homeTeam = document.getElementById("brazil").value
para.innerHTML = 'This is the national team of ' + `${homeTeam}` + ':'
<br> <input type="text" value="${homeTeam}" id="myInput"><button
onclick="myFunction()">Copy text</button>';
var element = document.getElementById("gugu");
element.appendChild(para)
}
})
document.getElementById("draw").addEventListener('click', function(e){
if(e.currentTarget.dataset.triggered) return;
e.currentTarget.dataset.triggered = true;
AppendFunction();
function AppendFunction() {
var para = document.createElement("p");
var homeTeam = document.getElementById("draw").value
para.innerHTML = 'This two teams have played each other 4 times ' +
`${homeTeam}` + ':' <br> <input type="text" value="${homeTeam}" id="myInput">
<button onclick="myFunction()">Copy text</button>';
var element = document.getElementById("gugu");
element.appendChild(para)
}
})
document.getElementById("russia").addEventListener('click', function(e){
if(e.currentTarget.dataset.triggered) return;
e.currentTarget.dataset.triggered = true;
AppendFunction();
function AppendFunction() {
var para = document.createElement("p");
var homeTeam = document.getElementById("russia").value
para.innerHTML = 'This is the national team of ' + `${homeTeam}` + ':'
<br> <input type="text" value="${homeTeam}" id="myInput"><button
onclick="myFunction()">Copy text</button>';
var element = document.getElementById("gugu");
element.appendChild(para)
}
})
PS: I don't know why the javascript code is not working in fiddle yet it is working on my computer.
If you look at the code I am basically trying to toggle a div with info on various teams. If it is Brazil the div comes with info on Brazil if Russia, info on Russia.
The problem with my current code is that it keep on appending the divs instead of
toggling them. How can I toggle them? like this: https://jsfiddle.net/YulePale/7jkuoc93/
Instead of having them append another div each time I click a different button?
............................................................................................
PS: EDIT & UPDATE:
#Twisty, I forked the code from your fiddle and tried to implement it when working with more than one row of buttons. The code works well but I was unable to append a different and separate element for each row each time I click on a button on that row.
I tried putting the appended element as a class:
Here is the code: https://jsfiddle.net/YulePale/a9L1nqvm/34/
Also tried putting it as an id:
Here is the code: https://jsfiddle.net/YulePale/a9L1nqvm/38/
How can I put it in a way that each row appends it's own separate element and I would also like users to be able to copy using the copy button without the element disappearing. How do I make it in such a way that the element only disappears only when I click outside the respective:
<div class="col.buttonCol " id="buttons-div">
and also disappears when I click another row of buttons?
Also in your answer you said you would have used text boxes instead of appending this way. I checked the modals out and they all appear on the browser like alerts can you please point me to a resource that show how you can use a modal that works like an appending element instead of one that acts as an alert? Thank you.
Here is the link to the modals I saw: https://getbootstrap.com/docs/4.0/components/modal/
I converted all your JavaScript to jQuery since you posted this in the jquery-ui, I am assuming you want to work with jQuery.
I will often organize my functions first and then the interactive actions.
JavaScript
$(function() {
function myFunction() {
//Do Stuff
}
function AppendFunction(id) {
var para = $("<p>");
var home = $("#" + id).val();
para.append("This is the national team of " + home + ":", $("<br>"), $("<input>", {
type: "text",
value: home,
id: "myInput"
}), $("<button>").html("Copy Text").click(myFunction));
$("#gugu").html(para);
}
function emptyOnDocumentClick(event) {
var action = $(".triggered").length;
$(".triggered").removeClass("triggered");
return !action;
}
$("#brazil, #russia").on('click', function(e) {
if ($(this).hasClass("triggered")) {
return;
}
$(this).addClass("triggered");
var myId = $(this).attr("id");
AppendFunction(myId);
});
$(document).on("click", function(e) {
if (emptyOnDocumentClick(e)) {
$("#gugu").html("");
}
});
});
Working Example: https://jsfiddle.net/Twisty/nruew82j/91/
The basic concept here is a dialog and if it were me, I would use a dialog box either from BootStrap or jQuery UI. You're not doing that, so we're create the content and append it to a specific <div>. Then, like in your previous question, you just detect a click on the document and decide what that will do. In this case, I emptied the content of the <div> that we'd previously appended content to.
Hope that helps.

Autocomplete for text area using entered values

I want to do autocomplete for textarea using entered values from browser. It is working for Textbox but not working Text area.
Normal textbox indeed get autocomplete behaviour for free.
As far as i know, you can get similar behaviour for textarea (even better, with all history) with installing lazarus plugin in your web browser.
Once installed, you will get a small cross icon on the top right corner. Clicking it will popup previous entries.
I usually don't like to install third party plugin in my web browser but this can save a lot of time and frustration when accidentally loosing all the text we already type.
First you need to include jquery UI then use the example code
HTML
<div class="ui-widget">
<label for="tags">Tags:</label>
<textarea id="tags" size="30"></textarea>
</div>
JS
$(function () {
$("document").ready(function () {
var availableTags = [
"ActionScript",
"AppleScript",
"Asp",
"BASIC",
"C",
"C++",
"Clojure",
"COBOL",
"ColdFusion",
"Erlang",
"Fortran",
"Groovy",
"Haskell",
"Java",
"JavaScript",
"Lisp",
"Perl",
"PHP",
"Python",
"Ruby",
"Scala",
"Scheme"];
$("#tags").on("keydown", function () {
var newY = $(this).textareaHelper('caretPos').top + (parseInt($(this).css('font-size'), 10) * 1.5);
var newX = $(this).textareaHelper('caretPos').left;
var posString = "left+" + newX + "px top+" + newY + "px";
$(this).autocomplete("option", "position", {
my: "left top",
at: posString
});
});
$("#tags ").autocomplete({
source: availableTags
});
});
});
You Need to use external plugin
Scripts and CSS
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<link rel="stylesheet" type="text/css" href="http://code.jquery.com/ui/1.10.4/themes/ui-lightness/jquery-ui.css"/>
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.10.4/jquery-ui.min.js"></script>
HTML
<textarea id="demo"></textarea>
Script
<script>
$(function() {
//Get the Data from a JSON or Hidden Feild
var availableTags = ["jQuery.com", "jQueryUI.com", "jQueryMobile.com", "jQueryScript.net", "jQuery", "Free jQuery Plugins"]; // array of autocomplete words
var minWordLength = 2;
function split(val) {
return val.split(' ');
}
function extractLast(term) {
return split(term).pop();
}
$("#demo") // jQuery Selector
// don't navigate away from the field on tab when selecting an item
.bind("keydown", function(event) {
if (event.keyCode === $.ui.keyCode.TAB && $(this).data("ui-autocomplete").menu.active) {
event.preventDefault();
}
}).autocomplete({
minLength: minWordLength,
source: function(request, response) {
// delegate back to autocomplete, but extract the last term
var term = extractLast(request.term);
if(term.length >= minWordLength){
response($.ui.autocomplete.filter( availableTags, term ));
}
},
focus: function() {
// prevent value inserted on focus
return false;
},
select: function(event, ui) {
var terms = split(this.value);
// remove the current input
terms.pop();
// add the selected item
terms.push(ui.item.value);
// add placeholder to get the comma-and-space at the end
terms.push("");
this.value = terms.join(" ");
return false;
}
});
});
</script>
DEMO LINK
ANOTHER PLUGIN TEXTEXTJS
Browsers do not currently support autocompletion for a textarea. The autocomplete attribute is formally allowed for textarea in HTML5 and it has the default value of on, but this value just means that browsers are allowed to use autocompletion. They do not actually use it for textareas, apparently because it would seldom be useful and could actually be confusing. It is much more probably that a user wants to reuse his address information, entered in single-line text input fields, than some longish text he has entered in, say, a feedback form of some site and now some other site happens to have a comments textarea with the same name.
Thus, all you can do is to set up some autocomplete functionality of your own. (This is what other answers suggest in various ways.) This means that you need to store user input somehow (which is what browsers do for their own autocompletion operations too), e.g. in cookies or in localStorage. This generally means that the functionality works inside a site, on pages using the same technique to implement it, but not across sites.

open mail sending prompt in new tab using mailto: [duplicate]

I have an image which when click, I want to link to a mailto:
<a id="mailto" href="mailto:hfms#live.com.my" target="_newtab" >
<img src="#Url.Content("~/Content/HomePage/email.png")" alt="email" /></a>
However, currently once its clicked, it will launch the email option to choose a mailto application, and once i choose, the mailto link is open in the current tab. This will cause user to leave the application.
So, I want the page to sent email (by gmail, yahoo, etc ) is either open in new tab or in a window. Any idea how to do this? I tried both target="_newtab" and target="_blank" but both didn't work.
Any help will be much appreciated.. Thanks...
(jQuery method is also acceptable if there is no other way, thanks)
this information is outdated, now it is possible to do so i believe, since gmail and others now work via browser links. there is however the problem that you would only want it to open in a new tab if NOT opening in a system mail client, and open in a new tab if it is a webmail client, otherwise for example Outlook users see a blank tab appear, which is disorienting, especially since they are Outlook users.
You don't need Javascript/Jquery for this. A standard link works (except Firefox v30+ due to a bug, see below).
<a href="mailto:example#example.com" target="_blank">
As of Firefox 30, does not work in Firefox due to a bug. It opens in the same tab AND replaces history so hitting back will not bring you back to the page where the mailto: link was.
This answer is based on this answer Open the href mailto link in new tab / window.
Right now, new browsers support some web mail interfaces (Like Gmail, Yahoo Mail, AoL, etc.).
So we can simply open a new window (Support older browser, new browsers just will open a new tab) and add a fallback (In case of non-javascript user) using preventDefault and default link redirection.
http://www.w3.org/TR/DOM-Level-2-Events/events.html#Events-flow-cancelation
https://developer.mozilla.org/es/docs/DOM/event.preventDefault
https://developer.mozilla.org/en-US/docs/Web/API/Window.open
Like so:
<a onClick="javascript:window.open('mailto:mail#domain.com', 'mail');event.preventDefault()" href="mailto:mail#domain.com">Send a e-mail</a>
http://jsfiddle.net/cNUNP/
Credit to https://stackoverflow.com/a/9880404/1107020
Guess that's all.
Greetings, Marcos.
mailto calls the users default email client. It does not open a window or tab in any instance. If you want to use a window or tab you need to configure a form and allow the form to open in your window/tab. Of course, you'll have to configure the form to send mail with whatever method is available on your server.
I know this is an old question, but this thread had the best set of answers if found. I modified Marcos's Answer above to also close the blank tab that is created if the client has an external mail handler
reference answer
JS (w\ jQuery for event handlers)
$(document).on('click', 'a[href^=mailto]', function(e) {
var checkClose, checkLoaded, event, href, i, len, loadEvents, results, t, wndw;
e.preventDefault();
href = this.href;
wndw = window.open(href, 'mail');
checkClose = function() {
console.log('checkClose');
try {
wndw.location.href;
return wndw.close();
} catch (error) {
return console.log('webmail');
}
};
t = setTimeout(checkClose, 5000);
try {
checkLoaded = function() {
console.log('loaded');
clearTimeout(t);
return t = setTimeout(checkClose, 2000);
};
wndw.onload = checkLoaded;
loadEvents = ["DomContentLoaded", "load", "beforeunload", "unload"];
results = [];
for (i = 0, len = loadEvents.length; i < len; i++) {
event = loadEvents[i];
results.push(wndw.addEventListener(event, checkLoaded));
}
return results;
} catch (error) {
return checkLoaded();
}
});
jsfiddle
Can confirm that '_blank' is still not working in Firefox for an emailto link. Instead use an onClick function that will do something like this:
window.open('mailto:'+email+'?subject='+subject);
Variant 1 (JavaScript):
<script>
// Open mailto links in a new tab
function mailto(email, subject, body) {
var url;
url = 'mailto:' + email;
url += '?subject=' + subject;
url += '&body=' + body;
window.open(url);
}
</script>
test#gmail.com
Variant 2 (JavaScript):
<script>
// Open mailto links in a new tab
function mailto(th) {
var url = th.getAttribute('href');
window.open(url);
}
</script>
test#gmail.com
Variant 3 (jQuery):
<script>
// Open mailto links in a new tab
$('#mailto').click(function (e) {
e.preventDefault();
var url = $(this).attr('href');
window.open(url);
});
</script>
test#gmail.com
Variant 4 (jQuery):
<script>
// Open mailto links in a new tab
$("a[href^='mailto:']").click(function(e) {
e.preventDefault();
var href = $(this).attr('href');
var target = $(this).attr('target');
window.open(href, target ? target : '_self');
});
</script>
test#gmail.com
HTML target Attribute: https://www.w3schools.com/tags/att_a_target.asp
Have you tried 'middle-click' ( "Open in new tab" ) ?
It works for me
(http://forums.mozillazine.org/viewtopic.php?f=7&t=1842595)
although it seems particularly strange to ask user to Middle click
Anyway I've found a pseudo solution that seems to work in FF 25/ Chrome 35
1.- Set up your link something like this:
<a href="javascript:void()"
class="mailToLink"
data-mail="mailaddr#domain.com">mailaddr#domain.com </a>
2.- Using javascript ( with jquery in the example) setup an onlclick event like:
$('.mailToLink').on('click', function(){
mailto=$(this).data('mail');
w=window.open('','_blank','',true);
w.location.href='mailto:'+mailto;
w.focus();
});
This opens a blank new window/tab and later changes its location, so the mail protocol handler is unable toto act until the new window is already opened
Not tested with Local mail client ( Outlook et al.)
There is a cheap html-hack to this problem.....
The link on one page...
Mail
On mailto.html....
<meta HTTP-EQUIV="REFRESH" content="0; url=mailto:who#website.com">
If nothing pops up click.....Mail!
_blank opens a new tab/window and the metatag does the rest. link as fallback offcourse.

How to open a new tab just after the current tab?

I'm developing a chrome extension and I want to open a new tab, but after the current tab that user is on. This is what I've tried to do:
function clickEvent(info, tab) {
update();
var url= "http://google.com";
var id = tab.id+1;
chrome.tabs.create({'url': url, 'index': id});
}
but the created tab opens at the end of tabs queue in chrome tab bar. After removing 'index': id from chrome.tabs.create, the result is same. I don't know how can I resolve the problem. Can anybody help me?
It sounds like you're creating a 'child' tab, in which case you should set both the index and the openerTabId:
function addChildTab(url, parentTab) {
chrome.tabs.create({
'url': url,
'windowId': parentTab.windowId,
'index': parentTab.index + 1, // n.b. index not id
'openerTabId': parentTab.id // n.b. id not index
});
}
Setting the openerTabId means that the new tab will properly be associated as a child tab of the parent tab, hence:
If you close the child tab while it is active, the parent tab will become the active tab (rather than, say, the tab to the right of the child tab). This makes it behave the same way as links that the user opens in new tabs.
Extensions that show tabs in a tree will work properly.
See also https://code.google.com/p/chromium/issues/detail?id=67539 which added this.
Note: if you're opening the tab in the background (by passing active:false), then parentTab.index + 1 isn't quite right, and instead ideally you'd insert the new tab after existing child (and grandchild) tabs of parentTab:
function addBackgroundChildTab(url, parentTab) {
chrome.tabs.query({'windowId': parentTab.windowId}, function(tabs) {
var parentAndDescendentIds = {};
parentAndDescendentIds[parentTab.id] = true;
var nextIndex = parentTab.index + 1;
while (nextIndex < tabs.length) {
var tab = tabs[nextIndex];
if (tab.openerTabId in parentAndDescendentIds) {
parentAndDescendentIds[tab.id] = true;
nextIndex++;
} else {
break;
}
}
chrome.tabs.create({
'url': url,
'active': false,
'windowId': parentTab.windowId,
'index': nextIndex,
'openerTabId': parentTab.id
});
});
}
But that may be overkill for your purposes, in which case sticking with parentTab.index + 1 as in my first code sample should be fine.
The tab is appended at the end because you're using the wrong argument (id should be index). The tab id is a positive integer which uniquely identifies tabs within a session. Consequently, the value of id is always higher than the number of tabs.
The position of the tab can be read from the index property. So, replace id with index:
function clickEvent(info, tab) {
update();
var url = "http://google.com/";
var index = tab.index + 1;
chrome.tabs.create({'url': url, 'index': index});
}