how to handle Foreground Notification message in Flutter web with FlutterFire - flutter

I'm using firebase_messaging in my flutter application and it works perfectly fine in both Android and IOS, but I have a strange problem in the web version as it only shows notifications on background, when am in the foreground it is not acting like getting a notification at all .. I know it is by default not showing Notification on foreground but am already handling this on both android and ios like this :
listenToForegroundMessages() {
FirebaseMessaging.onMessage.listen((RemoteMessage message) {
print('Got a message whilst in the foreground!');
print('Message data: ${message.data}');
if (message.notification != null) {
print('Message also contained a notification: ${message.notification}');
displayLocalNotification(
message.notification!.title!, message.notification!.body!);
}
});
}
That code is not affecting Web at all, as it not reacting to notifications at all , despite it is being shown perfectly when I don't have my web app open in the background
I have followed official flutterfire documentations for the web integration and here is the code I've used :
web/index.html
<!DOCTYPE html>
<html>
<head>
<!--
If you are serving your web app in a path other than the root, change the
href value below to reflect the base path you are serving from.
The path provided below has to start and end with a slash "/" in order for
it to work correctly.
For more details:
* https://developer.mozilla.org/en-US/docs/Web/HTML/Element/base
This is a placeholder for base href that will be replaced by the value of
the `--base-href` argument provided to `flutter build`.
-->
<base href="$FLUTTER_BASE_HREF">
<meta charset="UTF-8">
<meta content="IE=Edge" http-equiv="X-UA-Compatible">
<meta name="description" content="A new Flutter project.">
<!-- iOS meta tags & icons -->
<meta name="apple-mobile-web-app-capable" content="yes">
<meta name="apple-mobile-web-app-status-bar-style" content="black">
<meta name="apple-mobile-web-app-title" content="water_maps_flutter">
<link rel="apple-touch-icon" href="icons/Icon-192.png">
<!-- Favicon -->
<link rel="icon" type="image/png" href="favicon.png"/>
<title>water_maps_flutter</title>
<link rel="manifest" href="manifest.json">
</head>
<body>
<!-- This script installs service_worker.js to provide PWA functionality to
application. For more information, see:
https://developers.google.com/web/fundamentals/primers/service-workers -->
<script>
var serviceWorkerVersion = null;
var scriptLoaded = false;
function loadMainDartJs() {
if (scriptLoaded) {
return;
}
scriptLoaded = true;
var scriptTag = document.createElement('script');
scriptTag.src = 'main.dart.js';
scriptTag.type = 'application/javascript';
document.body.append(scriptTag);
}
if ('serviceWorker' in navigator) {
// Service workers are supported. Use them.
window.addEventListener('load', function () {
// ADD THIS LINE
navigator.serviceWorker.register('/firebase-messaging-sw.js');
// Wait for registration to finish before dropping the <script> tag.
// Otherwise, the browser will load the script multiple times,
// potentially different versions.
var serviceWorkerUrl = 'flutter_service_worker.js?v=' + serviceWorkerVersion;
navigator.serviceWorker.register(serviceWorkerUrl)
.then((reg) => {
function waitForActivation(serviceWorker) {
serviceWorker.addEventListener('statechange', () => {
if (serviceWorker.state == 'activated') {
console.log('Installed new service worker.');
loadMainDartJs();
}
});
}
if (!reg.active && (reg.installing || reg.waiting)) {
// No active web worker and we have installed or are installing
// one for the first time. Simply wait for it to activate.
waitForActivation(reg.installing || reg.waiting);
} else if (!reg.active.scriptURL.endsWith(serviceWorkerVersion)) {
// When the app updates the serviceWorkerVersion changes, so we
// need to ask the service worker to update.
console.log('New service worker available.');
reg.update();
waitForActivation(reg.installing);
} else {
// Existing service worker is still good.
console.log('Loading app from service worker.');
loadMainDartJs();
}
});
// If service worker doesn't succeed in a reasonable amount of time,
// fallback to plaint <script> tag.
setTimeout(() => {
if (!scriptLoaded) {
console.warn(
'Failed to load app from service worker. Falling back to plain <script> tag.',
);
loadMainDartJs();
}
}, 4000);
});
} else {
// Service workers not supported. Just drop the <script> tag.
loadMainDartJs();
}
</script>
<!-- <script src="https://www.gstatic.com/firebasejs/8.10.0/firebase-app.js"></script>-->
<script src="https://www.gstatic.com/firebasejs/8.4.1/firebase-analytics.js"></script>
<script defer src="https://www.gstatic.com/firebasejs/8.10.1/firebase-auth.js"></script>
<!-- <script defer src="https://www.gstatic.com/firebasejs/8.10.1/firebase-messaging.js"></script>-->
<script>
var firebaseConfig = {
apiKey: "*****",
authDomain: "*****",
projectId: "****",
storageBucket: "***",
messagingSenderId: "****",
appId: "***",
measurementId: "G-***"
};
firebase.initializeApp(firebaseConfig);
firebase.analytics();
</script>
<!--<script>-->
<!--if ("serviceWorker" in navigator) {-->
<!-- window.addEventListener("load", function () {-->
<!--navigator.serviceWorker.register("/firebase-messaging-sw.js");-->
<!-- });-->
<!--}-->
<!--</script>-->
</body>
</html>
web/firebase-messaging-sw.js
importScripts("https://www.gstatic.com/firebasejs/7.15.5/firebase-app.js");
importScripts("https://www.gstatic.com/firebasejs/7.15.5/firebase-messaging.js");
//Using singleton breaks instantiating messaging()
// App firebase = FirebaseWeb.instance.app;
firebase.initializeApp({
apiKey: "***************",
authDomain: "*************",
projectId: "**********",
storageBucket: "**********",
messagingSenderId: "*******",
appId: "******",
measurementId: "G-******"
});
const messaging = firebase.messaging();
messaging.usePublicVapidKey("**************")
messaging.setBackgroundMessageHandler(function (payload) {
const promiseChain = clients
.matchAll({
type: "window",
includeUncontrolled: true
})
.then(windowClients => {
for (let i = 0; i < windowClients.length; i++) {
const windowClient = windowClients[i];
windowClient.postMessage(payload);
}
})
.then(() => {
return registration.showNotification("New Message");
});
return promiseChain;
});
self.addEventListener('notificationclick', function (event) {
console.log('notification received: ', event)
});

Related

onMessage listener not working when main.dart executes in push notifications flutter web

I want to integrate push notifications in flutter. My web whole code is as:
my index.html code is as:
<html>
<title>Firebase Messaging Demo</title>
<style>
div {
margin-bottom: 15px;
}
</style>
<body>
<div id="token"></div>
<div id="msg"></div>
<div id="notis"></div>
<div id="err"></div>
<!-- The core Firebase JS SDK is always required and must be listed first -->
<script src="https://www.gstatic.com/firebasejs/8.4.2/firebase-app.js"></script>
<script src="https://www.gstatic.com/firebasejs/7.16.1/firebase-messaging.js"></script>
<script>
MsgElem = document.getElementById('msg');
TokenElem = document.getElementById('token');
NotisElem = document.getElementById('notis');
ErrElem = document.getElementById('err');
// TODO: Replace firebaseConfig you get from Firebase Console
var firebaseConfig = {
// apiKey: ...
// projectId: ...
// messagingSenderId: ...
// appId: ...
// ...other configs...
};
firebase.initializeApp(firebaseConfig);
const messaging = firebase.messaging();
messaging
.requestPermission()
.then(function () {
MsgElem.innerHTML = 'Notification permission granted.';
console.log('Notification permission granted.');
// get the token in the form of promise
return messaging.getToken();
})
.then(function (token) {
TokenElem.innerHTML = 'Device token is : <br>' + token;
})
.catch(function (err) {
ErrElem.innerHTML = ErrElem.innerHTML + '; ' + err;
console.log('Unable to get permission to notify.', err);
});
let enableForegroundNotification = true;
messaging.onMessage(function (payload) {
console.log('Message received. ', payload);
NotisElem.innerHTML =
NotisElem.innerHTML + JSON.stringify(payload);
if (enableForegroundNotification) {
let notification = payload.notification;
navigator.serviceWorker
.getRegistrations()
.then((registration) => {
registration[0].showNotification(notification.title);
});
}
});
</script>
</body>
and my firebase-messaging-sw.js code is as:
importScripts("https://www.gstatic.com/firebasejs/7.16.1/firebase-app.js");
importScripts(
"https://www.gstatic.com/firebasejs/7.16.1/firebase-messaging.js",
);
// For an optimal experience using Cloud Messaging, also add the Firebase SDK for Analytics.
importScripts(
"https://www.gstatic.com/firebasejs/7.16.1/firebase-analytics.js",
);
// Initialize the Firebase app in the service worker by passing in the
// messagingSenderId.
firebase.initializeApp({
messagingSenderId: "YOUR-SENDER-ID",
apiKey: "YOUR_API_KEY",
projectId: "YOUR_PROJECT_ID",
appId: "YOUR_APP_ID",
});
// Retrieve an instance of Firebase Messaging so that it can handle background
// messages.
const messaging = firebase.messaging();
messaging.setBackgroundMessageHandler(function(payload) {
console.log(
"[firebase-messaging-sw.js] Received background message ",
payload,
);
// Customize notification here
const notificationTitle = "Background Message Title";
const notificationOptions = {
body: "Background Message body.",
icon: "/itwonders-web-logo.png",
};
return self.registration.showNotification(
notificationTitle,
notificationOptions,
);
});
This whole code is working correct and but my dart screens not showing. And if I try to run my man.dart file then notifications donot work, only main.dart works.
Please give some suggestion or idea that how can I made them both to work.

Trying to post data via html-form and JavaScript to RESTapi – gets 404 Cannot Post?

I have googled a lot, gone through a lot of questions but can't find an answer.
I have built a simple RESTapi with node and mongoDB, using express and mongoose. The database is hosted on Atlas. The RESTapi works fine when accessing with postman, no problem there.
To access and use the RESTapi via the site I get the GET and DELETE method to work, but when trying to post data with a form I get the error “Cannot Post/ 404”. I have tried a lot of things but can´t get it to work. (I don't know it it is related, but the content-security policies which makes some scripts don't load, I have tried to allow everything in the head meta-info in index.html, but it doesn't make a change)
Request headers
Accept
text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8
Accept-Encoding
gzip, deflate
Accept-Language
en-US,en;q=0.5
Cache-Control
no-cache
Connection
keep-alive
Content-Length
530
Content-Type
multipart/form-data; boundary=---------------------------52045656921129358052645853016
Host
localhost:3000
Origin
http://localhost:3000
Pragma
no-cache
Referer
http://localhost:3000/
Upgrade-Insecure-Requests
1
The RESTapi and the site accessing is in the same folder, here is the project structure:
Here is the code:
js/main.js
window.onload = loadCourses();
// Variebles from the form
let formCreate = document.getElementById("formCreate");
let courseIdIn = document.getElementById("courseId");
let courseNameIn = document.getElementById("courseName");
let coursePeriodIn = document.getElementById("coursePeriod");
let message_form = document.getElementById("message_form");
const myForm = document.getElementById('formCreate');
myForm.addEventListener('submit', (e) => {
console.log('Hello from eventlistner');
e.preventDefault();
addCourse();
})
// GET courses
function loadCourses() {
$.getJSON("http://localhost:3000/courses", function(data) {
//rensa listan
console.log(data);
$("#tbody").html("");
for(let i = 0; i<data.length; i++) {
$("tbody").append("<tr><td>" + data[i]._id + "</td>" + "<td>"+ data[i].courseId + "</td>" + "<td>" + data[i].courseName +
"</td>" + "<td>" + data[i].coursePeriod + "</td>" + "<td><img class='deleteSize' onclick='deleteCourse(\""+data[i]._id+"\")' src='images/delete-photo.svg'alt='ikon radare'></td></tr>");
}
});
}
// DELETE course
function deleteCourse(id) {
console.log(id)
$.ajax({
type: "DELETE",
url: "http://localhost:3000/courses/" + id
}).done(function(response) {
console.log(response);
//ladda om listan
loadCourses();
});
}
// add course
function addCourse() {
console.log("Hi from add Course");
let courseIdEl = courseIdIn .value;
let courseNameEl = courseNameIn.value;
let coursePeriodEl = coursePeriodIn.value;
let courseObj =
{
"courseId": courseIdEl.value,
"courseName": courseNameEl.value,
"coursePeriod": coursePeriodEl.value
}
console.log(courseObj);
//Skapar fetch-anrop
fetch('http://localhost:3000/courses', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Accept': '*/*',
},
body: JSON.stringify(courseObj)
})
.then(response => response.json())
.then(data => {
// message
let message = data.message;
message_form.innerHTML = message;
//document.getElementById("message_form").innerHTML = message;
loadCourses();
formCreate.reset();
})
.catch(error => {
console.log('Error: ', error);
})
}
the index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="Content-Security-policy" content="default-src *;
script-src *;
connect-src *;">
<link rel="stylesheet" href="css/style.css">
<script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
<script src="js/main.js"></script>
<script src="main2.js"></script>
<title>Moment 3 - mongoose.js</title>
</head>
<body>
<h1>Moment 3 - mongoose.js</h1>
<table>
<thead>
<tr>
<th>ID</th>
<th>Kurs</th>
<th>Kursnamn</th>
<th>Period</th>
<th>Radera</th>
</tr>
</thead>
<tbody id="tbody">
<tr>
<td>1</td>
<td>DT162G</td>
<td>JavaScript-basar webbutveckling</td>
<td>1</td>
<td><img class="deleteSize" onclick="deleteCourse()" src="images/delete-photo.svg" alt="ikon radare">
</td>
</tr>
</tbody>
</table>
<h3>Create course:</h3>
<form class="forms" action="" id="formCreate" method="POST" enctype="multipart/form-data">
<!--fält för formulär, hela den grå delen-->
<fieldset id="field">
<p class="pfield" id="message_form"></p>
<label for="courseId">Kurskod:</label><br>
<input type="text" name="courseId" id="courseId" class="input">
<br>
<label for="courseName">Kursnamn:</label><br>
<input type="text" name="courseName" id="courseName" class="input">
<br>
<label for="coursePeriod">Kursperiod:</label><br>
<input type="number" id="coursePeriod" name="coursePeriod" min="1" max="2">
<div class="btn-wrapper">
<button type="submit" name="submitPost" id="btn-create" class="btn btn2">Publish</button>
<button type="reset" name="deletePost" id="btn-reset" class="btn btn2 btn-reset">Delete
field</button>
</div>
</fieldset>
</form>
</body>
</html>
RESTapi code
routes/courses.js
const express = require('express');
const router = express.Router();
// Hämtar schemamodel
const Courses = require('../models/CourseModel');
// Get all courses
router.get('/', async (req, res) => {
try {
const allCourses = await Courses.find();
if(!allCourses) {
throw Error('No items found');
} else {
res.status(200).json(allCourses);
}
} catch(err) {
res.status(500).json( {msg: err})
}
})
// GET one course
router.get('/:id', getCourse, (req, res) => {
res.json(res.course)
})
// Create course
router.post('/', async (req, res) => {
const newCourse = new Courses({
courseName: req.body.courseName,
courseId: req.body.courseId,
coursePeriod: req.body.coursePeriod
});
try {
const course = await newCourse.save();
if(!course) {
throw Error('Something went wrong while saving the post =( ');
} else {
// It worked ok, post is created
res.status(201).json(course);
}
} catch (err) {
// bad input from user = 400
res.status(400).json( {msg: err})
}
});
// UPDATE one course
router.patch('/:id', getCourse, async (req, res) => {
// options new = true makes mangoose send back updated data and not old
let options = { new: true };
try {
const course = await Courses.findByIdAndUpdate(req.params.id, req.body, options);
if(!course) {
throw Error ('Something went wrong while updating the post =( ');
} else {
// It worked ok, post is created
res.json(course).status(201).json( {success: true});
}
} catch {
res.status(400).json( {message: err.message})
}
})
// DELETE one course
router.delete('/:id', getCourse, async (req, res) => {
try {
await res.course.deleteOne();
res.status(200).json( {message: 'Success: Course is deleted!'})
} catch (err){
res.status(503).json( {message: err.message})
}
})
// Creating middlewhere function to re-use, findbyid. Middlewhere idé = webdev simplified
async function getCourse(req, res, next) {
let course;
try {
course = await Courses.findById(req.params.id)
if (course == null) {
return res.status(404).json( {message: 'Cant find any course with that ID'})
}
} catch (err) {
return res.status(500).json( {message: err.message})
}
res.course = course;
next();
}
module.exports = router;
models/CourseModel.js
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const CourseSchema = new Schema( {
courseName: {
type: String,
required: true
},
courseId: {
type: String,
required: true
},
coursePeriod: {
type: Number,
required: true
}
});
module.exports = mongoose.model('Courses', CourseSchema );
server.js
require('dotenv').config();
const express = require('express');
const app = express();
const path = require("path");
const mongoose = require('mongoose');
//const { MONGO_URI } = require('./config');
// Connect to MongoDB
mongoose.connect(process.env.MONGO_URI,{ useNewUrlParser: true, useUnifiedTopology: true, useFindAndModify: false })
.then(() => console.log('Connected to Mongo Database.'))
.catch(err => console.log(err));
//BodyParser Middleware, for use of JSON in body
app.use(express.json());
// skapa statisk sökväg
app.use(express.static(path.join(__dirname, 'public')));
// Routes
const courseRoutes = require('./routes/courses.js')
app.use('/courses', courseRoutes)
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => console.log (`Server run at port ${PORT}`));
well, it was a stupid mistake in HTML, the script source tag for the javascript-file main.js was in the head section. Of course, it must be in the bottom just before the body-tag. So stupid of me.

How to add annotations in video using video.js

is it possible to add annotation in my video using Video.js?
Below is my work out
<link href="http://vjs.zencdn.net/4.4/video-js.css" rel="stylesheet">
<script src="http://vjs.zencdn.net/4.4/video.js"></script>
<video id="my_video_1" class="video-js vjs-default-skin" controls
preload="auto" width="640" height="264" poster="my_video_poster.png"
data-setup="{}">
<source src="my_video.mp4" type='video/mp4'>
<source src="my_video.webm" type='video/webm'>
</video>
<script>
var Plugin = videojs.getPlugin('plugin');
var ExamplePlugin = videojs.extend(Plugin, {
constructor: function(player, options) {
Plugin.call(this, player, options);
player.on('timeupdate', function(){
var Component = videojs.getComponent('Component');
var TitleBar = videojs.extend(Component, {
constructor: function(player, options) {
Component.apply(this, arguments);
if (options.text)
{
this.updateTextContent(options.text);
}
},
createEl: function() {
return videojs.createEl('div', {
className: 'vjs-title-bar'
});
},
updateTextContent: function(text) {
if (typeof text !== 'string') {
text = 'hello world';
}
videojs.emptyEl(this.el());
videojs.appendContent(this.el(), text);
}
});
videojs.registerComponent('TitleBar', TitleBar);
var player = videojs('my-video');
player.addChild('TitleBar', {text: 'hellow people!'});
});
}
});
videojs.registerPlugin('examplePlugin', ExamplePlugin);
videojs('#my-video', {}, function(){
this.examplePlugin();
});
</script
</html>
//copy and paste this code it will surely work.

User is unknown on when FB.login is triggered

I am new to using the FB JS SDK so please bear with me..
I am currently trying to setup facebook login for a website. The problem I have is that when I click the login button and enter my login details facebook ONLY returns user info when I use the account I made the app on. When I use a different account response.authResponse returns a status of "unknown" which I find unusual.
The main function I'm reffering to here is this.loginUser.
I've also noticed that when I enter my details on the account I made the app on facebook will notify me that the app wants access to ... details however when I use a different account the login panel will disapear on login submit and not ask for permission.
Here is my code:
var FBUser = function(options) {
this.userInfo = null;
var that = this;
/* **********************************************
* Default parameter options
* **********************************************/
this.options = $.extend({
signInBtn: null,
messageContainer: null,
accountContainer: null
}, options);
/* **********************************************
* Initialise functions
* **********************************************/
this.init = function (){
//Load FB JS SDK
this.checkIfLoggedIn();
//Bind event handlers
this.bindEventHandlers();
};
//Check if user is already logged in, if so return data
this.checkIfLoggedIn = function(){
// Additional init code here
FB.getLoginStatus(function(response) {
if (response.status === 'connected') {
console.log("You logged in before so were retrieving your info...");
// the user is logged in and has authenticated your app
var uid = response.authResponse.userID;
var accessToken = response.authResponse.accessToken;
that.userInfo = response;
that.showUserInfo();
// connected
} else if (response.status === 'not_authorized') {
alert("not connected");
// not_authorized
} else {
// not_logged_in
}
});
};
//Run event handlers to window
this.bindEventHandlers = function() {
if(that.options.signInBtn !== null){
//Trigger fb Login
$(document).on("click", that.options.signInBtn, function(){
console.log("triggered get login");
that.loginUser();
});
}else{
console.log("Btn ID's are null");
}
};
//Trigger FB login
this.loginUser = function(){
FB.login(function(response) {
console.log("RESPONSE IS: ");
console.log(response);
if (response.authResponse) {
var access_token = FB.getAuthResponse()['accessToken'];
console.log('Access Token = '+ access_token);
console.log('Welcome! You just logged in. Fetching your information.... ');
that.userInfo = response;
that.showUserInfo();
} else {
// sign out
console.log('User does not grant extended permissions');
}
}, {scope: 'email, read_friendlists, user_birthday, user_location'});
};
//Show user info
this.showUserInfo = function (){
var info = this.userInfo;
if(this.userInfo){
FB.api('/me', function(info) {
console.log('Good to see you, ' + info.name);
console.log("USER DATA IS: ");
console.log(info);
//Append user info
if(that.options.messageContainer){
$(that.options.accountContainer).show();
$(that.options.messageContainer).html(info.name)
.prepend('<img src="https://graph.facebook.com/'+info.id+'/picture" alt="'+info.name+'">');
}else{
console.log("facebook container is null");
}
if(that.options.signInBtn){
$(that.options.signInBtn).hide();
}else{
console.log("Login button is null");
}
});
}
};
//Log user out
this.FBLogout = function(){
FB.logout(function(response) {
console.log("user is now logged out");
$(that.options.signInBtn).show();
$(that.options.accountContainer).hide();
});
};
return this.init();
};
/* **********************************************
* Initialise FB app
* **********************************************/
window.fbAsyncInit = function() {
FB.init({
appId : '', // App ID
channelUrl : ''
status : true, // check login status
cookie : true, // enable cookies to allow the server to access the session
xfbml : true, // parse XFBML
oauth : true
});
FB.Event.subscribe('auth.statusChange', function(response) {
alert('The status of the session is: ' + response.status);
});
/* **********************************************
* Initialise FB user object
* **********************************************/
//Make sure document is ready before creating object due to jquery references
$(document).ready(function (){
//FB initialise options
var FBUserOptions = {
signInBtn: '#fb_login',
messageContainer: '#welcome',
accountContainer: '#account_area'
};
//create FB user object
var fb_user = new FBUser(FBUserOptions);
});
};
/* **********************************************
* Load FB JS 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));
The HTML:
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>Facebook Login</title>
<script type="text/javascript" src="static/js/plugins/jquery-1.9.1.min.js"></script>
<script src="//connect.facebook.net/en_US/all.js"></script>
<script type="text/javascript" src="static/js/fb_login.js?=v33"></script>
<style type="text/css">
body{font-family: Arial, Helvetica, sans-serif;}
#account_area{display: none;}
</style>
</head>
<body>
<div id="fb-root"></div>
Login to facebook
<div id="account_area">
<div id="welcome"></div>
Sign out
</div>
</body>
</html>

facebook login button onclick event

I am add login button as shown below,but something go wrong. First two times I get facebook login window,but then something fails. When login window starts open it closed.When I step by step trace functions invoking I find thet onConnect() function is not invoking.Any ideas?
my View:
<script type="text/javascript">
$(document).ready(function () {
if (document.getElementById('fb-root') != undefined) {
var e = document.createElement('script');
e.type = 'text/javascript';
e.src = document.location.protocol + '//connect.facebook.net/en_US/all.js';
e.async = true;
document.getElementById('fb-root').appendChild(e);
}
});
window.fbAsyncInit = function () {
FB.init({ appId: '455724271129246', status: true, cookie: false, xfbml: true, oauth: true });
};
function onConnect() {
FB.getLoginStatus(function (response) {
if (response.session) {
window.location = "../LogOn/FbLogin?token=" + response.session.access_token;
} else {
// if user cancel
}
});
};
</script>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:fb="http://www.facebook.com/2008/fbml">
<body>
<div id="fb-root"></div>
<fb:login-button perms="email,user_checkins"
onlogin="onConnect();" autologoutlink="false">
</fb:login-button>
</body>
my controller:
public ActionResult FbLogin(string token)
{
WebClient client = new WebClient();
string JsonResult = client.DownloadString(string.Concat("https://graph.facebook.com/me?access_token=", token));
JObject jsonUserInfo = JObject.Parse(JsonResult);
UInt64 facebook_userID = jsonUserInfo.Value<UInt64>("id");
string username = jsonUserInfo.Value<string>("username");
string email = jsonUserInfo.Value<string>("email");
ViewData["email"] = email;
return View();
}
Try adding a subscribe event:
FB.Event.subscribe('auth.login', function (response) {
//do whatever
login();
// or onConnect();
});
FB.Event.subscribe('auth.logout', function (response) {
//do whatever
logout();
});