I want to send pushnotifications to firefox web browser.......
<script>
function notifyMe() {
// Let's check if the browser supports notifications
if (!("Notification" in window)) {
alert("This browser does not support desktop notification");
}
// Let's check whether notification permissions have already been granted
else if (Notification.permission === "granted") {
// If it's okay let's create a notification
var notification = new Notification("Hi there!");
}
// Otherwise, we need to ask the user for permission
else if (Notification.permission !== 'denied') {
Notification.requestPermission(function (permission) {
// If the user accepts, let's create a notification
if (permission === "granted") {
var notification = new Notification("Hi there!");
}
});
}
// At last, if the user has denied notifications, and you
// want to be respectful there is no need to bother them any more.
} Notification.requestPermission().then(function (result) {
console.log(result);
}); function spawnNotification(theBody, theIcon, theTitle) {
var options = {
body: theBody,
icon: theIcon
}
var n = new Notification(theTitle, options);
}
</script>
whenever first time my website run permission popup will come.but when user click allow button how to get browser info like id.I want save that browser id into my database.next time I will send notification using that id. I did not find any code please help me.please anyone help me.
The Web Notifications API does not do what think it does.
It can only be used to display notifications from a web page that a user currently has open in their browser. It is comparable to alert(), except with a larger variety of formatting options.
It is not a push notification service, and cannot be used as one.
Related
Background:
My project consists of a Vue 2 Front end encased in an electron shell with an asp.net core web API backend.
What I am trying to do is get a google authorization token and refresh token so that I can create a folder and files within that folder on a users google drive. I also want to display a list of the folders content in my front end.
I have tried using the new Google Identity Services code in my front end but when launching my app and clicking on the google button I the following error
Error 400: invalid_request
If you’re the app developer, make sure that these request details comply with Google policies:
redirect_uri: storagerelay://file/?id=auth12850
I think this is because electron is seen more of a desktop app which according to the google documentation needs to use a loopback address to open the system browser and authenticate from there.
So I tried the google authentication api on my backend which is C# I have the google web authorization broker setup and when I run my backend and call my endpoint I get the google sign in page and can get the authorization token and refresh token.
Question:
Is there a way to capture the URL of the page that comes up for authentication so that I can put it in a child window in electron.
or a way to pass the data to the front end so that I can show the list of files to my users.
Would I still need to use a loopback address even though I am getting the authentication page from the web broker?
If I do need the loopback functionality would I be better off using the data from the Google Desktop Application example rather than the google Web broker?
To learn more about electron you can go Electron website.
For a web app I think your going to have an issue
Users will be redirected to this path after they have authenticated with Google. The path will be appended with the authorization code for access, and must have a protocol. It can’t contain URL fragments, relative paths, or wildcards, and can’t be a public IP address.
Not just because of the format but because its going to need to be a domain you can register.
If you go with an installed app then the redirect uri is https://127.0.0.1
Im not sure how you are going to get this to route back properly.
I ended up using the nodejs google api to get this working this is my code that now returns an auth token and refresh token.
This code opens a child window when the authorize button is clicked and loads the google login/account select. Once authorized it shows the app permission window. When a user clicks allow the url is invoked in the loopback of the created server and the auth file is created in the specified directory.
part one successful.. now on to getting everything else working.
/* Google authentication */
function createGoogleWindow() {
const http = require('http');
const path = require('path');
const service = google.drive('v3');
const TOKEN_DIR = path.join(process.env.APPDATA, 'home-inventory', 'bin');
const TOKEN_PATH = path.join(TOKEN_DIR, 'home-inventory.json');
const querystring = require('querystring');
let googleWindow = new BrowserWindow({
parent: win,
height: 600,
width: 400,
webPreferences: {
webSecurity: false,
nodeIntegration: true,
enableRemoteModule: true,
contextIsolation: false
}
});
if (isDevelopment) googleWindow.webContents.openDevTools();
googleWindow.menuBarVisible = false;
googleWindow.on('closed', () => {
googleWindow = null;
});
const oauth2Client = new google.auth.OAuth2(
CLIENT_ID,
CLIENT_SECRET,
REDIRECT_URI
);
// check if we previously stored a token
fs.readFile(TOKEN_PATH, function (err, token){
if (err) {
getNewToken(oauth2Client);
} else {
oauth2Client.credentials = JSON.parse(token);
callback(oauth2Client);
}
});
const url = oauth2Client.generateAuthUrl({
access_type: 'offline',
scope: SCOPES
});
function callback (auth) {
service.files.list({
auth: auth,
q: `name contains '.bak'`,
pageSize: 50,
fields: "nextPageToken, files(id,name,size,parents,createdTime)",
}, function(err, response) {
if (err) {
console.error('The API returned an error: ', err);
return;
}
const files = response.files;
if (files.length === 0) {
console.warn('no files found');
} else {
console.warn('files', files, auth.credentials.access_token);
}
});
}
function getNewToken(oauth2Client, callback) {
function storeToken(token) {
try {
fs.mkdirSync(TOKEN_DIR);
} catch (err) {
if (err.code !== 'EEXIST') {
throw err
}
}
fs.writeFile(TOKEN_PATH, JSON.stringify(token), (err) => {
if (err) {
throw err;
}
// console.debug('file was saved successfully');
googleWindow.close();
});
// console.warn('Token stored to: ', TOKEN_PATH);
}
function handler(request, response, server, callback) {
let qs = querystring.parse(require('url').parse(request.url).query);
oauth2Client.getToken(qs.code, function (err, tokens) {
if (err) {
console.error('Error getting oAuth tokens: ', err);
}
oauth2Client.credentials = tokens;
storeToken(tokens);
callback(oauth2Client)
server.close();
});
}
const server = http.createServer(function (request, response) {
handler(request, response, server, callback);
}).listen(8181, function() {
googleWindow.loadURL(url);
})
}
}
I added a Facebook login in my app. When I log in in my application it also logs in toSAFARI so that next time when I want to login, I don't need to enter login and password. You might press continue and you already login. I created a method to log out but it's not working. Its working in a simulator so I can close my app then open Safari and go to Facebook.com then press logout. Finally I open my app press press the Facebook login and got login and password fields.
public void Logout()
{
_loginManager.LogOut();
NSHttpCookieStorage storage = NSHttpCookieStorage.SharedStorage;
foreach (NSHttpCookie cookie in storage.Cookies)
{
if(cookie.Domain == ".facebook.com")
{
storage.DeleteCookie(cookie);
}
}
}
How can I log out from FB to every time enter login and password?
This image show that my credentials already entered:
You are maybe looking for methods and classes from WebKit instead. Also refer to this Forum post: https://forums.xamarin.com/discussion/149720/delete-web-cache-javascript-storage
You can get cookies and sessions with (there are more types in WKWebsiteDataType if there are other things you want to clear):
var websiteDataTypes = new NSSet<NSString>(
WKWebsiteDataType.Cookies,
WKWebsiteDataType.SessionStorage);
Or you can use WKWebsiteDataStore.AllWebsiteDataTypes to just clear everything.
You can then fetch these types with:
WKWebsiteDataStore.DefaultDataStore.FetchDataRecordsOfTypes()
It has a callback you need to listen to, to get these. Then you can remove all these records with:
WKWebsiteDataStore.DefaultDataStore.RemoveDataOfTypes();
Put it all together like:
var websiteDataTypes = new NSSet<NSString>(
WKWebsiteDataType.Cookies,
WKWebsiteDataType.SessionStorage);
WKWebsiteDataStore.DefaultDataStore.FetchDataRecordsOfTypes(websiteDataTypes, records =>
{
for (nuint i = 0; i < records.Count; i++)
{
var record = records.GetItem<WKWebsiteDataRecord>(i);
WKWebsiteDataStore.DefaultDataStore.RemoveDataOfTypes(
record.DataTypes,
new[] {record},
() => {}
);
}
});
I have a news site that is powered by C# ASP.Net MVC 5.0 and I want to push notification to clients browser when an admin add/edit or delete a news.
so I added a signalr script to my template which is used in all pages.
_Layout.cshtml
var notificationsHub = $.connection.notificationHub;
$.connection.hub.start();
jQuery(function($) {
notificationsHub.client.Toast = function (title, body) {
var options = {
body: body,
};
var notification = new Notification(title, options);
};
});
and added this code to the page that redirects after news add/edit/delete is done
<script>
$.connection.hub.start().done(function() {
notificationsHub.server.toast('#NotificationHub.Type.ToString()', '#Html.Raw(NotificationHub.Title)', '#Html.Raw(NotificationHub.Body)');
});
</script>
when I add/edit/delete a news it works fine but the problem is it pushes notification to all opened tabs in my site. is there a trick to avoid this happening and show only one browser notification per site?
Then you have to know the number of open tabs and the URL used. See the "How to get the number of tabs opened of my web in a browser using jquery?" SO question for a discussion that this is not desired for privacy reasons.
OK I found answer in this SO question.
The trick is to use tag in options:
var notificationsHub = $.connection.notificationHub;
$.connection.hub.start();
jQuery(function($) {
notificationsHub.client.Toast = function (title, body) {
var options = {
body: body,
tag: 'my-unique-id',
};
var notification = new Notification(title, options);
};
});
For my app, I'm using a webview. I have implemented the notifications by following this tutorial :
http://www.raywenderlich.com/32960/apple-push-notification-services-in-ios-6-tutorial-part-1
In my website I use a js code that check new event added in the db:
function checkNotification()
{
$.ajax({
url: '/checkNewMessages',
type: "GET",
success: function (result)
{
// if new event, then I run the #c code below to tell
// the APN server to send the notif to the device.
}
});
}
To send the notifications I'm using a #c code:
var deviceToken = "2191a536a52445046797a871fe3c4cf...";
var message = "this is a notification.";
var badge = 1;
var password = "blablabla";
var payload = new NotificationPayload(deviceToken, message, badge);
var notificationList = new List<NotificationPayload>() { payload };
var push = new PushNotification(true, "apn_developer_identity.p12", password);
var result = push.SendToApple(notificationList);
And I check this every 10000 milisec
setInterval(checkNotification, 10000);
But this js code will be running only when the user is on the app. What's happen when the app is not running ? The user won't be able to receive the notifications ? I need a script always running in background checking new event on my db. What is the best way to do this ? Thanks for your help.
Push notification are handled by iOS not your app, thus when your server send a push notification to an users app they will just receive it.
Only when you the user opens the app using the notification is it possible to detect the notification used to open the app. You check for the notification used to open the on the
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
NSDictionary *remoteNotif =[launchOptions objectForKey:UIApplicationLaunchOptionsRemoteNotificationKey];
if (remoteNotif) {
/* handle the notification.
}
}
There is not way to monitor push notification in the background.
This is the script on my webpage:
<div id="fb-root"></div>
<script>
window.fbAsyncInit = function () {
FB.init({
appId: '419349611446911', // App ID
status: true, // check login status
cookie: true, // enable cookies to allow the server to access the session
xfbml: true // parse XFBML
});
// Additional initialization code here
FB.Event.subscribe('auth.authResponseChange', function (response) {
if (response.status === 'connected') {
// the user is logged in and has authenticated your
// app, and response.authResponse supplies
// the user's ID, a valid access token, a signed
// request, and the time the access token
// and signed request each expire
var uid = response.authResponse.userID;
var accessToken = response.authResponse.accessToken;
// TODO: Handle the access token
// Do a post to the server to finish the logon
// This is a form post since we don't want to use AJAX
var form = document.createElement("form");
form.setAttribute("method", 'post');
form.setAttribute("action", '#Url.Action("FacebookLogin", "Account")');
var field = document.createElement("input");
field.setAttribute("type", "hidden");
field.setAttribute("name", 'accessToken');
field.setAttribute("value", accessToken);
form.appendChild(field);
document.body.appendChild(form);
form.submit();
} else if (response.status === 'not_authorized') {
// the user is logged in to Facebook,
// but has not authenticated your app
} else {
// the user isn't logged in to Facebook.
}
});
};
// Load the SDK Asynchronously
(function (d) {
var js, id = 'facebook-jssdk', ref = d.getElementsByTagName('script')[0];
if (d.getElementById(id)) { return; }
js = d.createElement('script'); js.id = id; js.async = true;
js.src = "//connect.facebook.net/en_US/all.js";
ref.parentNode.insertBefore(js, ref);
} (document));
</script>
And here is my :LogOnPartial:
#if(Request.IsAuthenticated) {
<text>Hola, <strong>#User.Identity.Name</strong>!
[ #Html.ActionLink("Log Off", "LogOff", "Account") ]</text>
}
else {
<div class="fb-login-button" data-show-faces="false" data-width="200" data-max-rows="1"></div>
}
When I change to auth.login clicking the login button doesn't log in or even redirect anywhere. Just a small flash of loading and nothing else. When I use auth.authReponseChange, I can correctly log in using Facebook, but the page reloads over and over again.
What I'm asking is, how can I fix this bug? And why is the auth.authResponseChange event being fired every single time?
Example:
I log out of my local website:
FormsAuthentication.SignOut();
And even then, the Facebook button auto logs me in, and the loop continues. What is firing the login button click?
Please try change the event subscribe from FB.Event.subscribe('auth.authResponseChange' to
"auth.login". This will trigger your code only the first time when user login in.
Below is taken from fb documentations
auth.login
This event is fired when your app first notices the user (in other words, gets a session when it didn't already have a valid one).
auth.logout
This event is fired when your app notices that there is no longer a valid user (in other words, it had a session but can no longer validate the current user).
auth.authResponseChange
This event is fired for any auth related change as they all affect the session: login, logout, session refresh. Sessions are refreshed over time as long as the user is active with your app.
auth.statusChange
Typically you will want to use the auth.authResponseChange event. But in rare cases, you want to distinguish between these three states:
Connected
Logged into Facebook but not connected with your
application Not logged into Facebook at all.