Trouble using Notification API js - javascript

I'm facing an issue trying to implement notifications in my website.
In fact, I'm trying to make a function that calls PHP with an ajax request, in order to check with mysql if there are any notification. Then, if there is one/few notification(s), I get back from PHP the information I need, and display them using notification API. I do this every 5 seconds.
In fact, notifications are displayed in the top right corner, and I can only see the bottom of it.
Other weird fact, when I use function alert();, notifications are properly displayed.. This issue is happening with Firefox, but not on chromium.
So my question is, do you have any idea why notifications are not placed properly on firefox but not on Chromium? If you need any more information do not hesitate. Thanks in advance, and if you need it, here is some code :
With this two functions, I get what I need thanks to a php script.
function notifications() {
$.ajax({ url: './get_notifications.php/',
type: 'post',
data: {"name": window.user},
success: function(output) {
if (output != "")
{
split_notifications(output);
}
else
return;
},
failure: function() {
console.log("failed");
}
});
}
function check_notifications() {
setInterval(function() {
notifications();
}, 10000);
}
In this function, I just split information and then call another function, in charge of creating my notification.
function split_notifications(notif) {
var tmp_notif = notif.split(";");
var index = 0;
while (tmp_notif[0].split(",,,")[index])
{
//!\\ When I put alert() HERE it's working
display_notification(tmp_notif[1].split(",,,")[index], tmp_notif[2].split(",,,")[index], tmp_notif[0].split(",,,")[index]);
index += 1;
}
}
Here is the function that creates my notification :
function display_notification(title, message, someone) {
{
if(window.Notification && Notification.permission !== "denied") {
Notification.requestPermission(function(status) { // status is "granted", if accepted by user
var project_notification = new Notification(title, {
body: someone + " " + message + '\nSee more...',
icon: "../img/" + someone.split(" ")[1] + ".png"
});
project_notification.onclick = function() {
alert("");
}
});
}
}

Related

JavaScript callback / async problem? Background script of Chrome Extension stops function before finishing

I am trying to create a small crawler as a chrome extension. How it works is:
Open new window or tab.
Perform a search for Google / Google News / YouTube with given keywords.
Store information of the results in a small database
I first created and tested the functions with a popup.html. There it works perfectly.You click on a button and all pages are visited and the results are stored in a database. But I want to start the program without clicking anything first. That's why I migrated it to background.js. There it also works, but only if the Service Worker / DevTool console is open. Only then it runs completely.
I would be grateful for any helpful answer.
const keywords = [
"Keyword1",
"Keyword2",
// ...
"Keyword13"
];
chrome.runtime.onStartup.addListener(() => {
chrome.tabs.onUpdated.addListener(loadingWindow);
openWindow();
});
// Opens new Window or Tab with the correct URL
function openWindow() {
chrome.tabs.onUpdated.addListener(loadingWindow);
if (runs == 0) {
chrome.windows.create({ url: getUrl(keywords[runs]), type: "normal" }, newWindow => {
window_id = newWindow.id;
});
} else {
chrome.tabs.update(tab_id, { url: getUrl(keywords[runs]) });
}
}
// Wait to load the new tab
function loadingWindow(tabId, changeInfo, tab) {
if (changeInfo.status === 'complete' && tab.status == 'complete' && tab.windowId == window_id) {
tab_id = tabId;
console.log(tab.windowId);
chrome.tabs.onUpdated.removeListener(loadingWindow);
chrome.tabs.sendMessage(tab.id, { text: source }, doStuffWithDom);
}
};
// Get information from content script -> payload and then send to database
function doStuffWithDom(domContent) {
let payload = {... }
var data = new FormData();
data.append("json", JSON.stringify(payload));
fetch(".../store.php", { method: "POST", body: data });
crawlDone();
}
// open new window / tab or close the open window
function crawlDone() {
runs++;
if (runs < keywords.length) {
openWindow();
} else if (runs == keywords.length) {
chrome.windows.remove(window_id);
}
};
I switched to Manifest version 2. Then I could include the Background.js via the Background.html, which also runs to the end.

Send multiple messages using google chrome console

I want to test message functionality in my browser game. Instead of sending messages manually to 50 test accounts I thought maybe I can do it automatically in Chrome console.
For first I would make a for loop.
for (i=0; i > 50; i++)
{
//to do
}
I would use my games link to fill the sending form
game.php?page=messages&mode=write&id=1&subject=message_test
ID is for user ids and Subject fill the subject area.
In my message send template I use this JavaScript to send a message
function check(){
if($('#text').val().length == 0) {
alert('{$LNG.mg_empty_text}');
return false;
} else {
$('submit').attr('disabled','disabled');
$.post('game.php?page=messages&mode=send&id={$id}&ajax=1', $('#message').serialize(), function(data) {
alert(data);
parent.$.fancybox.close();
return true;
});
}
}
Maybe someone can help me how to execute a function using Chrome console and send out messages? Maybe put me to a proper tutorial.
if you want to "export" your functions to the console into the google chrome or another dev tools, you can export it to a window object, so
// create a namespace to have all functions under your custom namespace
window.MyCustomNS = {};
window.MyCustomNS.yourFunction = function(id, dataObject) {
if($('#text').val().length == 0) {
alert('{$LNG.mg_empty_text}');
return false;
} else {
$('submit').attr('disabled','disabled');
$.post('game.php?page=messages&mode=send&id=' + + '&ajax=1', $.param(dataObject), function(data) {
alert(data);
parent.$.fancybox.close();
return true;
});
}
};
then into the console you try this,
window.MyCustomNS.yourFunction('YOUR_ID', { name: 'some parameter', another: 'another parameter' });

Editing A Table In MVC using Javascript

I am very new to MVC and coding. I have a table that I created in using MVC, but I am wanting to hook up JavaScript to enable inline editing and post back to the database. I think I have been watching too many tutorials, that I am now confused on how to even execute this. Is there anyone out there who could give me a launch in the right direction as to how to begin connecting JavaScript so that I can accomplish inline editing.
Here is how I resolved my question. This is for anyone who is wanting to know how to do inline editing of a table that you created using html.
Here is my code for the function I created once you clicked on Edit:
function editThis(element) {
var customerID = $(element).closest('tr').find('.customer-stored- id').attr('data-value');
GetByID("Home/Edit", customerID, replaceCustomerRow, element);
}
This function replaces the row
function replaceCustomerRow(result, element) {
$(element).closest('tr').replaceWith(result);
}
This function will get the ID
function GetByID(url, id, callback, param1) {
$.ajax({
url: "../../" + url + "/" + id,
type: "GET",
success: function (result) {
if (callback != null && callback != undefined) {
callback(result, param1);
}
},
error: function (result) {
if (result.responseText != '') {
alert(result.responseText);
}
else {
alert("An error occurred while processing results. Please consult an administrator.");
}
}
})
}
Then you would just write your code for the controller. Simple enough, but it works.

Javascript behaves differently when called from custom ribbon button vs onSave

I'm trying to add versioning functionality to a custom entity, MFAs, and I'm running into a very odd problem. I have a javascript webresource being called from two places: an onSave event on the form, and as the action of a custom ribbon button. Specifically, the onSave event calls captureSave, while the ribbon button calls makeARevision.
When called from the save button/event, everything works as expected; all information, including the new changes, are pulled to a new record and saved there, while the original record is closed without the changes being saved, and without a prompt to save. However, when called via the custom ribbon button, any unsaved changes do not get brought over to the new record, and the old record prompts for saving. Furthermore, even if the user chooses to save the changes to the old record, the changes are not saved, and the form doesn't automatically close.
The following code is the webresource in question. company_MFASaveOrRevise is just an html page that asks the user whether they want to save the record or create a new revision. Any ideas on what's causing the differences or how to resolve them is appreciated.
function captureSave(executionContext) {
if (Xrm.Page.ui.getFormType() != 1 && Xrm.Page.data.entity.getIsDirty()) {
var retVal = showModalDialog(Xrm.Page.context.getServerUrl() + '/Webresources/company_MFASaveOrRevise', null, 'dialogWidth: 300px; dialogHeight: 100px');
if (retVal == "Revise") {
executionContext.getEventArgs().preventDefault();
makeARevision();
}
else if (retVal == "Save") {
}
}
}
function createLookupValue(oldLookup) {
var lookupVal = new Object();
lookupVal.Id = oldLookup.id;
lookupVal.LogicalName = oldLookup.entityName;
lookupVal.Name = oldLookup.Name;
return lookupVal;
}
function makeARevision() {
var revisedMFA = {};
revisedMFA['company_mfaname'] = Xrm.Page.data.entity.attributes.get('company_mfaname').getValue();
revisedMFA['company_mfadate'] = Xrm.Page.data.entity.attributes.get('company_mfadate').getValue();
revisedMFA['company_estimatedliqdate'] = Xrm.Page.data.entity.attributes.get('company_estimatedliqdate').getValue();
revisedMFA['company_actualliqdate'] = Xrm.Page.data.entity.attributes.get('company_actualliqdate').getValue();
revisedMFA['company_mfanumber'] = Xrm.Page.data.entity.attributes.get('company_mfanumber').getValue();
revisedMFA['company_revisionno'] = Xrm.Page.data.entity.attributes.get('company_revisionno') == null ? 0 : Xrm.Page.data.entity.attributes.get('company_revisionno').getValue() + 1;
revisedMFA['company_requester'] = createLookupValue(Xrm.Page.data.entity.attributes.get('company_requester').getValue()[0]);
revisedMFA['company_mfapreviousrev'] = Xrm.Page.data.entity.attributes.get('company_totalmfatodate').getValue();
revisedMFA['company_contract'] = createLookupValue(Xrm.Page.data.entity.attributes.get('company_contract').getValue()[0]);
$.ajax({
type: 'POST',
contentType: 'application/json; charset=utf-8',
datatype: 'json',
url: getODataUrl() + '/' + 'company_mfaSet',
data: JSON.stringify(revisedMFA),
beforeSend: function (XMLHttpRequest) {
//Specifying this header ensures that the results will be returned as JSON.
XMLHttpRequest.setRequestHeader('Accept', 'application/json');
},
success: function (data, textStatus, request) {
Xrm.Utility.openEntityForm("company_mfa", data.d.company_mfaId.toUpperCase());
var attributes = Xrm.Page.data.entity.attributes.get();
for (var i in attributes) {
attributes[i].setSubmitMode('never');
}
Xrm.Page.ui.close();
},
error: function (request, textStatus, errorThrown) {
alert(errorThrown);
//alert("There was an error creating the revision");
}
});
}
Edit: I had debugger; inserted in various places and was using VS2012 debugger, and found that the attributes were being properly set not to submit, but apparently that didn't stop the confirmation dialog from popping up (even though it works when the webresource is called through the save button). Additionally, Xrm.Page.data.entity.attributes.get(attributeName) returns the post-changes values when called during onSave event, but pre-change values when called from the ribbon. I still don't know why or how to fix it though. Is there something else I should look for?
Use F12 to debug your code when being called from the ribbon (just remember since it is in the ribbon, your javascript code will be in a dynamic script / script block).

Jquery too many ajax request fired

I have the following code build using jquery. When a user copies and pastes a a youtube url, i am suppose to extract the video id is the getVideoId(str) method in jquery. Using the id, i get the video image picture title and contents.
When the textbox->("#url") has a length more than 10, i will make a ajax request. Thus the ajax request is working. But now i have another problem. The very first time when the textbox has more than 10 characters, there is two ajax request being fired (tested using firebug). Than when the user enters more characters, there are many ajax request fired.
Thus this will slow down the process of the last ajax request. I just want to get the data of the youtube link and show a suggest where the user can add the title and content. It is like how the old facebook video video link is. Anyone has a better suggest in improving the codes?
jQuery(document).ready(
function(){
$("#url").keyup(function() {
var $t1 = $("#url").val();
var $length = $t1.length;
var $data;
$("#title").val($length);
$("#content").val($t1);
if($length==0){
alert('zero value');
return;
}
if($length>10){
$data = $.ajax({
url: '<?php echo $this->Html->url(array("action" => "retrieveVideoFeed"));?>',
dataType: "json",
data: {
vid: getVideoId($t1)
},
success: function(data) {
alert('success in getting data');
}
});
return;
}
});
function getVideoId(str) {
var urlRegex = /(http|https):\/\/(\w+:{0,1}\w*#)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%#!\-\/]))?/;
if (urlRegex.test(str) && str.indexOf('v=') != -1)
{
return str.split('v=')[1].substr(0, 11); // get 11-char youtube video id
} else if (str.length == 11) {
return str;
}
return null;
}
}
);
You could cache the calls and use blur event and not keyup: you are firing a lot of AJAX call because keyup() fires an event each time a key is pressed, you should use blur that fires an event when an input loses focus.
If you cache the calls in an object you can avoid a lot of repeated calls
var cacheUrl = {};
$("#url").blur(function() {
var $t1 = $("#url").val();
var $length = $t1.length;
var $data;
$("#title").val($length);
$("#content").val($t1);
if($length==0){
alert('zero value');
return;
}
if(cacheUrls[$t1] !== undefined && $length>10){
$data = $.ajax({
url: '<?php echo $this->Html->url(array("action" => "retrieveVideoFeed"));?>',
dataType: "json",
data: {
vid: getVideoId($t1)
},
success: function(data) {
//save the data to avoid a future call
cacheUrls[$t1] = data;
alert('success in getting data');
}
});
return;
}elseif ($length>10){
//you already have the data in cacheUrls[$t1]
}
});
EDIT if you want to use the submit key to start the search you could trigger the blur event when you press enter like this:
$("#url").keypress(function(e){
if(e.which == 13){
$(this).blur();
return false;
}
});
I think many ajax requests are fired because you are using $("#url").keyup(function()
so that for every key event in url input the particular funciton will exectue.So, as per i know better to use focusout method instead of keyup.
If you stay with the keyup-Event you maybe want to use an ajaxmanager-plugin for jQuery which can manage queues or limits the number of simultaneous requests.
$.manageAjax.create('myAjaxManager', {
queue: true,
cacheResponse: false,
maxRequests: 1,
queue: 'clear'
});
....
if($length>10){
$data = $.manageAjax.add({ ...
This will prevent having alot of ajaxrequests active at the same time when the user is typing. As soon as he stops the request will not aborted and the results will show up.

Categories

Resources