FB.api only loads on first AJAX call to page - javascript

I have an issue with an FB.api only loading the first time a page is retrieved via AJAX. FB.getLoginStatus does work though.
Demo page: http://proof.ptly.com/test/fb/test-ajax.htm (clicking the load link works the first time but fails the second time it is clicked)
Expected/Desired behaviour: after giving permission to the app, it should list of all groups or pages associated to the user
Current behaviour: group list is only populated on first load. subsequent clicks do not load the list (FB.api does not return a response - view console for logging)
The reason behind this problem is that the page I am retrieving (test.htm) can't be changed but the page I am calling it from (test-ajax.htm) can. While I know this method isn't pretty nor ideal, I'm wondering if it is possible to overcome. Thus suggestions to change the underlying test.htm, while correct, won't solve the problem I'm having.
Sample code
Main page that calls the AJAX page
<html>
<head>
<title>My Facebook Login Page</title>
<script type="text/javascript" language="javascript" src="js/jquery.js"></script>
<script>
var loaded = false;
jQuery(document).ready(function(){
jQuery("#lnk").click(function(e){
e.preventDefault();
jQuery("#divContent").load("test.htm", function(){
if(loaded)
{
FB.getLoginStatus(FBverifyLogin);
}
else
{
loaded = true;
}
});
});
});
</script>
</head>
<body>
<a href="#" id='lnk'>load</a>
<div id='divContent'></div>
</body>
</html>
AJAX page being retrieved
<script type="text/javascript">
var FB_config = {
API_ID: "347798778614308",
PERMISSIONS: "publish_stream,manage_pages,user_groups",
};
(function(d){
var js, id = 'facebook-jssdk'; if (d.getElementById(id)) {return;}
js = d.createElement('script'); js.id = id; js.async = true;
js.src = "//connect.facebook.net/en_US/all.js";
d.getElementsByTagName('head')[0].appendChild(js);
}(document));
jQuery(document).ready(function(){
// initialise FB
window.fbAsyncInit = function() {
FB.init({
appId : '347798778614308',
status : true,
cookie : true,
xfbml : true,
oauth : true
});
FB.Event.subscribe('auth.statusChange', FBverifyLogin);
};
});
function FBverifyLogin(response) {
console.log("FBverifyLogin");
console.log(response);
jQuery("#FBreauth").hide();
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;
ShowPostToFacebookCheckbox();
FBdisplayMyPages(response.authResponse);
jQuery("#btnLogin").hide();
checkPermissions();
} else if (response.status === 'not_authorized') {
} else {
// the user isn't logged in to Facebook.
jQuery("#btnLogin").show();
return false;
}
}
function checkPermissions(){
console.log("checkPermissions");
FB.api('/me/permissions', function(response) {
console.log("in checkPermissions fb.api");
console.log(response);
var permissions = FB_config.PERMISSIONS.split(",");
for(var i = 0; i < permissions.length; i++)
{
if(response.data[0][permissions[i]] == undefined || response.data[0][permissions[i]] != 1)
{
jQuery("#FBreauth").show();
break;
}
}
});
}
function FBdisplayMyPages(authResponse){
console.log("FBdisplayMyPages");
console.log(authResponse);
FB.api('/me/accounts', function(response) {
console.log("in FBdisplayMyPages fb.api");
console.log(response);
var str = "";
var name = "";
var count = 0;
str += '<optgroup label="Pages">';
for(var i = 0; i < response.data.length; i++)
{
if(response.data[i].category != "Application")
{
name = response.data[i].name;
str += '<option value="'+response.data[i].id+"_"+response.data[i].access_token+'">'+name+'</option>';
count++;
}
}
str += "</optgroup>";
jQuery("#msgPostOn").html(str);
FB.api('/me/groups', function(response) {
console.log("in FBdisplayMyPages fb.api 2");
console.log(response);
str = jQuery("#msgPostOn").html();
str += '<optgroup label="Groups">';
name = "";
for(var i = 0; i < response.data.length; i++)
{
if(response.data[i].category != "Application")
{
name = response.data[i].name;
str += '<option value="'+response.data[i].id+"_"+authResponse.accessToken+'">'+name+'</option>';
count++;
}
}
str += "</optgroup>";
jQuery("#msgPostOn").html(str);
switch(count)
{
case 0:
// notify that there are not pages. will post to personal page
str += '<option value="' + authResponse.userID + "_" + authResponse.accessToken + '">Personal Account</option>';
jQuery("#msgPostOn").html(str);
jQuery("#FBpostTo").text("No pages found. Posting to your personal account");
jQuery("#FBpostTo").show();
break;
case 1:
// only 1 page. hide it...
// notify name of page to update
jQuery("#msgPostOn").hide();
jQuery("#FBpostTo").html("Posting to <strong>" + name + "</strong>");
jQuery("#FBpostTo").show();
break;
default:
// notify user to select a page to post to
jQuery("#FBpostTo").text("There are multiple groups/pages associated with your account. Specify which to post to ");
jQuery("#FBpostTo").show();
jQuery("#msgPostOn").show();
}
});
});
}
function FBrefresh(){
console.log("FBrefresh");
FB.getLoginStatus(FBverifyLogin);
}
function FBreauth(){
console.log("FBreauth");
FB.ui(
{
method: 'oauth',
display: 'popup',
app_id: FB_config.API_ID,
client_id: FB_config.API_ID,
redirect_uri: "http://www.facebook.com/connect/login_success.html",
scope: FB_config.PERMISSIONS
}
);
}
function ShowPostToFacebookCheckbox()
{
console.log("ShowPostToFacebookCheckbox");
jQuery('#postToFacebook2').css('display', 'inline');
jQuery('#LabelForFacebook').css('display', 'inline');
}
</script>
<div id="fb-root"></div>
<div id="postToFacebookField" class="fieldContainer checkbox ">
<div id="btnLogin" class="fb-login-button" scope="publish_stream,manage_pages,user_groups">Login with Facebook</div>
<input type="checkbox" style="display:none" name="postToFacebook2" value="on" id="postToFacebook2">
<label style="cursor: pointer; display:none" for="postToFacebook2" id="LabelForFacebook">Post to Facebook Page</label>
<div id="FBpostTo" style="display: none"></div>
<select id="msgPostOn" style="display: none"></select>
<div style="display: none" id="FBreauth">(Insufficient permissions. <a href ='#' onclick='FBreauth(); return false;'>Authorize this app</a> and <a href='#' onclick='FBrefresh() ; return false'>refreshing</a>)</div>
</div>

If you are still looking for a solution to this problem, I believe I have something that might work within the constraints that you have set. Quite simply, we just clear all the loaded variables and objects in memory, and from my tests, including the <script> that facebook attaches.
Replace the click handler in test.htm with this and it should work
jQuery(document).ready(function(){
jQuery("#lnk").click(function(e){
if(FB && document.getElementById("facebook-jssdk")){ //if set, reset
//removes the <script>
document.head.removeChild(document.getElementById("facebook-jssdk"));
window.FB=null; //unloads the APIs
loaded=null;
}
e.preventDefault();
jQuery("#divContent").load("test.htm", function(){
if(loaded)
{
FB.getLoginStatus(FBverifyLogin);
}
else
{
loaded = true;
}
});
});
});

We had a similar kind of issue, this post http://www.martincarlin.info/facebook-js-sdk-not-working-on-second-load-of-ajax-loaded-page/ helped us to resolve the issue.
The reason the script was not working was because the window.fbAsyncInit function runs on the initial page load and so the second time you do your AJAX call, the Facebook JavaScript SDK is already loaded in your page so window.fbAsyncInit doesn’t fire again.
By checking if FB is already defined we can then use our SDK code without the initialisation part.
Hope that will help you to resolve the issue.

After trying everything from past few days this below piece of code worked for me.
//intialize FB object (this is useful if you are using Turbolinks)
$(document).on('page:load', function(){
intializeFB();
});
intializeFB();
function intializeFB(){
if(typeof(FB) !== "undefined"){
delete FB;
}
$.getScript("http://connect.facebook.net/en_US/all.js#xfbml=1", function () {
FB.init({
appId : '19871816653254',
cookie : true, // enable cookies to allow the server to access
// the session
xfbml : true, // parse social plugins on this page
oauth : true,
status : true,
version : 'v2.4' // use version 2.4
});
});
}
Hope this is useful!

Related

Simple WebRTC webpage works well in Chrome and Safari, but not in Firefox

Background
I am building a local area network, WebRTC baby monitor with a raspberry pi camera module and USB microphone. The stream is synthesized with GStreamer and im using Janus Gateway to facilitate the WebRTC connection between a web browser and the Pi. The webpage and Javascript is a stripped down version of the streaming demo provided by Meetecho.
This is my first time using many of these technologies and am a bit in over my head with troubleshooting at the moment. I'm having trouble figuring out why the web page works in Chrome and Safari, but does not work in Firefox.
It works fine on Chrome and Safari:
In Firefox, the WebRTC connection seems to be successfully established and maintained (based on comparisons of the network traffic and console output between Chrome and Firefox), but the page seems to get caught up somewhere along the way:
Comparing the consoles
When comparing the console outputs of Chrome and Firefox, they are identical until this point where both consoles report Uncaught (in promise) DOMException: but for possibly different reasons?
Firefox says Uncaught (in promise) DOMException: The fetching process for the media resource was aborted by the user agent at the user's request.
Chrome says Uncaught (in promise) DOMException: The play() request was interrupted by a new load request.
Are these the same errors with different "Hints"? Or are they actually different errors due to some underlying difference between the browsers?
Immediately after this error, Firefox diverges from Chrome by reporting Remote track removed.
Im unsure if I am doing something silly in the JS to cause this or if there is some nuance about Firefox that I am missing.
Other details that might be helpful?
Below is part of the html (index.html) and javascript (janus_stream.js) for the page, the pastebin link contains the whole janus_stream.js.
// We make use of this 'server' variable to provide the address of the
// REST Janus API. By default, in this example we assume that Janus is
// co-located with the web server hosting the HTML pages but listening
// on a different port (8088, the default for HTTP in Janus), which is
// why we make use of the 'window.location.hostname' base address. Since
// Janus can also do HTTPS, and considering we don't really want to make
// use of HTTP for Janus if your demos are served on HTTPS, we also rely
// on the 'window.location.protocol' prefix to build the variable, in
// particular to also change the port used to contact Janus (8088 for
// HTTP and 8089 for HTTPS, if enabled).
// In case you place Janus behind an Apache frontend (as we did on the
// online demos at http://janus.conf.meetecho.com) you can just use a
// relative path for the variable, e.g.:
//
// var server = "/janus";
//
// which will take care of this on its own.
//
//
// If you want to use the WebSockets frontend to Janus, instead, you'll
// have to pass a different kind of address, e.g.:
//
// var server = "ws://" + window.location.hostname + ":8188";
//
// Of course this assumes that support for WebSockets has been built in
// when compiling the server. WebSockets support has not been tested
// as much as the REST API, so handle with care!
//
//
// If you have multiple options available, and want to let the library
// autodetect the best way to contact your server (or pool of servers),
// you can also pass an array of servers, e.g., to provide alternative
// means of access (e.g., try WebSockets first and, if that fails, fall
// back to plain HTTP) or just have failover servers:
//
// var server = [
// "ws://" + window.location.hostname + ":8188",
// "/janus"
// ];
//
// This will tell the library to try connecting to each of the servers
// in the presented order. The first working server will be used for
// the whole session.
//
var server = null;
if(window.location.protocol === 'http:')
server = "http://" + window.location.hostname + ":8088/janus";
else
server = "https://" + window.location.hostname + ":8089/janus";
var janus = null;
var streaming = null;
var opaqueId = "streamingtest-"+Janus.randomString(12);
var bitrateTimer = null;
var spinner = true;
var simulcastStarted = false, svcStarted = false;
var selectedStream = null;
$(document).ready(function() {
// Initialize the library (all console debuggers enabled)
Janus.init({debug: "all", callback: function() {
// Use a button to start the demo
//$('#start').one('click', function() {
//$(this).attr('disabled', true).unbind('click');
// Make sure the browser supports WebRTC
if(!Janus.isWebrtcSupported()) {
bootbox.alert("No WebRTC support... ");
return;
}
// Create session
janus = new Janus(
{
server: server,
success: function() {
// Attach to Streaming plugin
janus.attach(
{
plugin: "janus.plugin.streaming",
opaqueId: opaqueId,
success: function(pluginHandle) {
$('#details').remove();
streaming = pluginHandle;
Janus.log("Plugin attached! (" + streaming.getPlugin() + ", id=" + streaming.getId() + ")");
// Setup streaming session
$('#update-streams').click(updateStreamsList);
updateStreamsList();
$('#start').removeAttr('disabled').html("Stop")
.click(function() {
$(this).attr('disabled', true);
clearInterval(bitrateTimer);
janus.destroy();
$('#streamslist').attr('disabled', true);
$('#watch').attr('disabled', true).unbind('click');
$('#start').attr('disabled', true).html("Bye").unbind('click');
});
},
error: function(error) {
Janus.error(" -- Error attaching plugin... ", error);
bootbox.alert("Error attaching plugin... " + error);
},
iceState: function(state) {
Janus.log("ICE state changed to " + state);
},
webrtcState: function(on) {
Janus.log("Janus says our WebRTC PeerConnection is " + (on ? "up" : "down") + " now");
},
onmessage: function(msg, jsep) {
Janus.debug(" ::: Got a message :::", msg);
var result = msg["result"];
if(result) {
if(result["status"]) {
var status = result["status"];
if(status === 'starting')
$('#status').removeClass('hide').text("Starting, please wait...").show();
else if(status === 'started')
$('#status').removeClass('hide').text("Started").show();
else if(status === 'stopped')
stopStream();
} else if(msg["streaming"] === "event") {
// Is simulcast in place?
var substream = result["substream"];
var temporal = result["temporal"];
if((substream !== null && substream !== undefined) || (temporal !== null && temporal !== undefined)) {
if(!simulcastStarted) {
simulcastStarted = true;
addSimulcastButtons(temporal !== null && temporal !== undefined);
}
// We just received notice that there's been a switch, update the buttons
updateSimulcastButtons(substream, temporal);
}
// Is VP9/SVC in place?
var spatial = result["spatial_layer"];
temporal = result["temporal_layer"];
if((spatial !== null && spatial !== undefined) || (temporal !== null && temporal !== undefined)) {
if(!svcStarted) {
svcStarted = true;
addSvcButtons();
}
// We just received notice that there's been a switch, update the buttons
updateSvcButtons(spatial, temporal);
}
}
} else if(msg["error"]) {
bootbox.alert(msg["error"]);
stopStream();
return;
}
if(jsep) {
Janus.debug("Handling SDP as well...", jsep);
var stereo = (jsep.sdp.indexOf("stereo=1") !== -1);
// Offer from the plugin, let's answer
streaming.createAnswer(
{
jsep: jsep,
// We want recvonly audio/video and, if negotiated, datachannels
media: { audioSend: false, videoSend: false, data: true },
customizeSdp: function(jsep) {
if(stereo && jsep.sdp.indexOf("stereo=1") == -1) {
// Make sure that our offer contains stereo too
jsep.sdp = jsep.sdp.replace("useinbandfec=1", "useinbandfec=1;stereo=1");
}
},
success: function(jsep) {
Janus.debug("Got SDP!", jsep);
var body = { request: "start" };
streaming.send({ message: body, jsep: jsep });
$('#watch').html("Stop").removeAttr('disabled').click(stopStream);
},
error: function(error) {
Janus.error("WebRTC error:", error);
bootbox.alert("WebRTC error... " + error.message);
}
});
}
},
onremotestream: function(stream) {
Janus.debug(" ::: Got a remote stream :::", stream);
var addButtons = false;
if($('#remotevideo').length === 1) {
addButtons = true;
//$('#stream').append('<video class="rounded centered hide" id="remotevideo" width="100%" height="100%" playsinline/>');
$('#remotevideo').get(0).volume = 0;
// Show the stream and hide the spinner when we get a playing event
$("#remotevideo").bind("playing", function () {
$('#waitingvideo').remove();
if(this.videoWidth)
$('#remotevideo').removeClass('hide').show();
if(spinner)
spinner.stop();
spinner = null;
var videoTracks = stream.getVideoTracks();
if(!videoTracks || videoTracks.length === 0)
return;
var width = this.videoWidth;
var height = this.videoHeight;
$('#curres').removeClass('hide').text(width+'x'+height).show();
if(Janus.webRTCAdapter.browserDetails.browser === "firefox") {
// Firefox Stable has a bug: width and height are not immediately available after a playing
setTimeout(function() {
var width = $("#remotevideo").get(0).videoWidth;
var height = $("#remotevideo").get(0).videoHeight;
$('#curres').removeClass('hide').text(width+'x'+height).show();
}, 2000);
}
});
}
Janus.attachMediaStream($('#remotevideo').get(0), stream);
$("#remotevideo").get(0).play();
$("#remotevideo").get(0).volume = 1;
var videoTracks = stream.getVideoTracks();
if(!videoTracks || videoTracks.length === 0) {
// No remote video
$('#remotevideo').hide();
if($('#stream .no-video-container').length === 0) {
$('#stream').append(
'<div class="no-video-container">' +
'<i class="fa fa-video-camera fa-5 no-video-icon"></i>' +
'<span class="no-video-text">No remote video available</span>' +
'</div>');
}
} else {
$('#stream .no-video-container').remove();
$('#remotevideo').removeClass('hide').show();
}
if(!addButtons)
return;
if(videoTracks && videoTracks.length &&
(Janus.webRTCAdapter.browserDetails.browser === "chrome" ||
Janus.webRTCAdapter.browserDetails.browser === "firefox" ||
Janus.webRTCAdapter.browserDetails.browser === "safari")) {
$('#curbitrate').removeClass('hide').show();
bitrateTimer = setInterval(function() {
// Display updated bitrate, if supported
var bitrate = streaming.getBitrate();
$('#curbitrate').text(bitrate);
// Check if the resolution changed too
var width = $("#remotevideo").get(0).videoWidth;
var height = $("#remotevideo").get(0).videoHeight;
if(width > 0 && height > 0)
$('#curres').removeClass('hide').text(width+'x'+height).show();
}, 1000);
}
},
ondataopen: function(data) {
Janus.log("The DataChannel is available!");
$('#waitingvideo').remove();
$('#stream').append(
'<input class="form-control" type="text" id="datarecv" disabled></input>'
);
if(spinner)
spinner.stop();
spinner = null;
},
ondata: function(data) {
Janus.debug("We got data from the DataChannel!", data);
$('#datarecv').val(data);
},
oncleanup: function() {
Janus.log(" ::: Got a cleanup notification :::");
$('#waitingvideo').remove();
$('#remotevideo').remove();
$('#datarecv').remove();
$('.no-video-container').remove();
$('#bitrate').attr('disabled', true);
$('#bitrateset').html('Bandwidth<span class="caret"></span>');
$('#curbitrate').hide();
if(bitrateTimer)
clearInterval(bitrateTimer);
bitrateTimer = null;
$('#curres').hide();
$('#simulcast').remove();
$('#metadata').empty();
$('#info').addClass('hide').hide();
simulcastStarted = false;
}
});
},
error: function(error) {
Janus.error(error);
bootbox.alert(error, function() {
window.location.reload();
});
},
destroyed: function() {
window.location.reload();
}
});
//});
}});
});
function updateStreamsList() {
$('#update-streams').unbind('click').addClass('fa-spin');
var body = { request: "list" };
Janus.debug("Sending message:", body);
streaming.send({ message: body, success: function(result) {
setTimeout(function() {
$('#update-streams').removeClass('fa-spin').click(updateStreamsList);
}, 500);
if(!result) {
bootbox.alert("Got no response to our query for available streams");
return;
}
if(result["list"]) {
$('#streams').removeClass('hide').show();
$('#streamslist').empty();
$('#watch').attr('disabled', true).unbind('click');
var list = result["list"];
Janus.log("Got a list of available streams");
if(list && Array.isArray(list)) {
list.sort(function(a, b) {
if(!a || a.id < (b ? b.id : 0))
return -1;
if(!b || b.id < (a ? a.id : 0))
return 1;
return 0;
});
}
Janus.debug(list);
for(var mp in list) {
Janus.debug(" >> [" + list[mp]["id"] + "] " + list[mp]["description"] + " (" + list[mp]["type"] + ")");
$('#streamslist').append("<li><a href='#' id='" + list[mp]["id"] + "'>" + list[mp]["description"] + " (" + list[mp]["type"] + ")" + "</a></li>");
}
$('#streamslist a').unbind('click').click(function() {
selectedStream = $(this).attr("id");
$('#streamset').html($(this).html()).parent().removeClass('open');
return false;
});
$('#watch').removeAttr('disabled').unbind('click').click(startStream);
}
}});
}
function getStreamInfo() {
$('#metadata').empty();
$('#info').addClass('hide').hide();
if(!selectedStream)
return;
// Send a request for more info on the mountpoint we subscribed to
var body = { request: "info", id: parseInt(selectedStream) || selectedStream };
streaming.send({ message: body, success: function(result) {
if(result && result.info && result.info.metadata) {
$('#metadata').html(result.info.metadata);
$('#info').removeClass('hide').show();
}
}});
}
function startStream() {
selectedStream = "1"
Janus.log("Selected video id #" + selectedStream);
if(!selectedStream) {
bootbox.alert("Select a stream from the list");
return;
}
$('#streamset').attr('disabled', true);
$('#streamslist').attr('disabled', true);
$('#watch').attr('disabled', true).unbind('click');
var body = { request: "watch", id: parseInt(selectedStream) || selectedStream};
streaming.send({ message: body });
// No remote video yet
$('#stream').append('<video class="rounded centered" id="waitingvideo" width="100%" height="100%" />');
if(spinner == null) {
var target = document.getElementById('stream');
spinner = new Spinner({top:100}).spin(target);
} else {
spinner.spin();
}
// Get some more info for the mountpoint to display, if any
getStreamInfo();
}
function stopStream() {
$('#watch').attr('disabled', true).unbind('click');
var body = { request: "stop" };
streaming.send({ message: body });
streaming.hangup();
$('#streamset').removeAttr('disabled');
$('#streamslist').removeAttr('disabled');
$('#watch').html("Watch or Listen").removeAttr('disabled').unbind('click').click(startStream);
$('#status').empty().hide();
$('#bitrate').attr('disabled', true);
$('#bitrateset').html('Bandwidth<span class="caret"></span>');
$('#curbitrate').hide();
if(bitrateTimer)
clearInterval(bitrateTimer);
bitrateTimer = null;
$('#curres').empty().hide();
$('#simulcast').remove();
simulcastStarted = false;
}
.......
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>BabyPi Cam</title>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/webrtc-adapter/7.4.0/adapter.min.js" ></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.9.1/jquery.min.js" ></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.4.1/js/bootstrap.min.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/bootbox.js/5.4.0/bootbox.min.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/spin.js/2.3.2/spin.min.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/toastr.js/2.1.4/toastr.min.js"></script>
<script type="text/javascript" src="janus.js" ></script>
<script type="text/javascript" src="janus_stream.js"></script>
<script>
$(function() {
$(".navbar-static-top").load("navbar.html", function() {
$(".navbar-static-top li.dropdown").addClass("active");
$(".navbar-static-top a[href='streamingtest.html']").parent().addClass("active");
});
$(".footer").load("footer.html");
});
</script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootswatch/3.4.0/cerulean/bootstrap.min.css" type="text/css"/>
<link rel="stylesheet" href="css/demo.css" type="text/css"/>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css" type="text/css"/>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/toastr.js/2.1.4/toastr.min.css"/>
</head>
<body>
<div class="container">
<div class="col-md-12">
<div class="panel panel-default">
<div class="panel-heading">
<h3 class="panel-title">BabyPi Live Stream
<span class="label label-info" id="status"></span>
<span class="label label-primary" id="curres"></span>
<span class="label label-info" id="curbitrate" styple="display:inline;"></span>
</h3>
</div>
<div class="panel-body" id="stream">
<video class="rounded centered" id="remotevideo" width="100%" height="100%" playsinline controls muted></video>
</div>
</div>
</div>
</div>
</body>
</html>
I am also using the janus.js API provided Meetecho
The Questions
What am I doing wrong that prevents this from working in Firefox?
What can the diverging console outputs tell me about what I am doing wrong?
Do you have any suggestions on where to look / what to try to get this working in Firefox?
Any pointers or ideas are greatly appreciated! Please let me know if I can provide other information.
Thank you!
Update: Theory / Possible answer?
In an attempt to address the Uncaught (in promise) DOMException: The fetching process for the media resource was aborted by the user agent at the user's request. error, I changed video.play() to video.load(). This addressed the error, but the same Remote track removed and "No remote video" behavior persists.
In the meantime I may have discovered the more fundamental issue: The video stream from the Pi is H264, and from what I can tell, Firefox does not support this format? Perhaps this is the reason that I am having issues with firefox?
Can any of you confirm or deny this as the true issue?
The issue is related to H264 incompatibility, but after seeing this thread I realized i was a victim of the same issue.
I needed to update one line in my janus.plugin.streaming.jcfg file so that it looks like this:
RPI3: {
type = "rtp"
id = 1
description = "Raspberry Pi 3 Infrared Camera Module stream"
video = true
videoport = 5001
videopt = 96
videortpmap = "H264/90000"
videofmtp = "profile-level-id=42e01f;packetization-mode=1"
audio = true
audioport = 5002
audiopt = 111
audiortpmap = "opus/48000/2"
}
Previously I was using this "incomplete" line which was causing the issue:
...
videofmtp = "packetization-mode=1"
...
Apparently this enables the correct H264 "profile" that can work with Firefox's OpenH264 plugin. Now i am able to view the stream with both chrome and firefox!

Trying to share cookie between domains using common iframe but get two cookies instead

I have a situation where I have two different sites, siteA.com and siteB.com, which need to share a common piece of information when a visitor navigates from siteA to siteB. I don't have access to the server-side code or navigation links from siteA, only limitied customizations and javascript. In order to share the information I have built a new page that is fully under my control at siteC.com, and then added this page as an iframe to both siteA and siteB. I am using the postMessage method to get and set the cookie from within the iframe which is working fine from each site, however I actually end up with two different cookies, one for each siteA and siteB even though the cookie belongs to siteC because it was set by the page in the iframe, confirmed through F12 debugger. I would have expected to have a single cookie and both sites could share the same cookie via the iframe, am I missing something here, should this be possible or is there another way to do this?
This is the code for my page at siteC that gets loaded into the iframe
<!DOCTYPE html>
<html>
<head>
<title>iframe source</title>
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<script type="text/javascript">
$(function () {
var ck = document.cookie;
var expDate = new Date();
expDate.setFullYear(expDate.getFullYear() + 20)
$("#auditlog").append("iframe loaded<br/>");
if (ck) {
$("#auditlog").append("cookie exists<br/>");
} else {
$("#auditlog").append("cookie not set<br/>");
}
// Assign handler to message event
if (window.addEventListener) {
window.addEventListener('message', messageHandler, false);
} else if (window.attachEvent) { // ie8
window.attachEvent('onmessage', messageHandler);
}
})
function messageHandler(e) {
var msg = {};
var response;
// Check origin
if (e.origin === 'http://siteA' || e.origin === 'http://siteB') {
// Retrieve data sent in postMessage
msg = JSON.parse(e.data);
if (msg.action == "getCookie") {
response = getCookie();
} else if (msg.action == "setCookie") {
setCookie(msg.payload);
response = "cookie set";
} else {
response = "action not supported";
}
// Send reply to source of message
e.source.postMessage(response, e.origin);
}
}
function setCookie(cookieVal) {
var expDate = new Date();
expDate.setFullYear(expDate.getFullYear() + 20)
document.cookie = cookieVal + "; expires=" + expDate.toUTCString();
}
function getCookie() {
return document.cookie;
}
</script>
</head>
<body>
<div id="auditlog"></div>
<div id="cookieinfo"></div>
</body>
</html>
And this is code for my pages at siteA and siteB, both are using this same code, this is a sample I set up in order to test the set and get cookie functions in the iframe
<!DOCTYPE html>
<html>
<head>
<title>Main content page</title>
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<script type="text/javascript">
$(function () {
// Assign handler to message event
if (window.addEventListener) {
window.addEventListener('message', messageHandler, false);
} else if (window.attachEvent) { // ie8
window.attachEvent('onmessage', messageHandler);
}
$("#btnGetIframeCookie").click(function () {
var postMsg = {
action:"getCookie"
}
// get reference to window inside the iframe
var wn = document.getElementById('cookieiframe').contentWindow;
// postMessage arguments: data to send, target origin
wn.postMessage(JSON.stringify(postMsg), 'http://siteC');
})
$("#btnSetIframeCookie").click(function () {
var cookieVal = $("#txtCookieValue").val();
var postMsg = {
action: "setCookie",
payload: cookieVal
}
var wn = document.getElementById('cookieiframe').contentWindow;
// postMessage arguments: data to send, target origin
wn.postMessage(JSON.stringify(postMsg), 'http://siteC');
})
})
function messageHandler(e) {
if (e.origin === 'http://siteC') {
$("#divMessages").append("response from iframe: <br/>" + e.data + "<br/>");
}
}
</script>
</head>
<body>
<div>
This is the iframe container
</div>
<div>
<input type="button" id="btnGetIframeCookie" value="Get iframe cookie" />
</div>
<div>
<input type="text" size="60" id="txtCookieValue" />
<input type="button" id="btnSetIframeCookie" value="Set iframe cookie" />
</div>
<iframe id="cookieiframe" src="http://siteC/iframe/index.html" style="width: 300px; height: 300px; border:1px solid black;"></iframe>
<div id="divMessages"></div>
</body>
</html>
Using this setup, if I set a cookie from siteA via the iframe with a value of "keyabc=value123" for example, I can then read that same cookie back, but when I go to siteB which has the same page in the iframe there, I don't have a cookie until I set one there, for example "keyabc=value456". Now if I look at my actual cookie files at C:\Users\aakoehle\AppData\Local\Packages\Microsoft.MicrosoftEdge_8wekyb3d8bbwe\AC\#!001\MicrosoftEdge\Cookies I see two files, one with each of the values I set and both have the path of siteC. I also launched the F12 tools for each browser tab, each tab shows it's own cookie belonging to siteC.
-- UPDATE --
With the current version of my code posted here I am now only seeing the cookie issue in the Edge browser. Chrome and IE are sharing a single cookie between siteA and siteB as expected.
Here's an example for sharing data between cross origin sites, using localStorage and postMessage.
site1 : localhost:9091
<html>
<body>
<h1>site 1</h1>
<button id='postBtn'>Post message</button>
<br/>
<iframe id='commonSite' src='http://localhost:9093/commonSite.html' style='height:150px'></iframe>
<script>
(function () {
var commonSite = document.querySelector('#commonSite').contentWindow;
var postCounter = localStorage.getItem('postCounter');
postCounter = postCounter != null ? +postCounter : 1;
var commonOrigin = 'http://localhost:9093';
document.querySelector('#postBtn').onclick = function () {
commonSite.postMessage(postCounter++, commonOrigin);
localStorage.setItem('postCounter', postCounter);
console.log('site 1 posted');
}
})();
</script>
</body>
</html>
site2: localhost:9092
<html>
<body>
<h1>site 2</h1>
<button id='postBtn'>Post message</button>
<br/>
<iframe id='commonSite' src='http://localhost:9093/commonSite.html' style='height:150px'></iframe>
<script>
(function () {
var commonSite = document.querySelector('#commonSite').contentWindow;
var postCounter = localStorage.getItem('postCounter');
postCounter = postCounter != null ? +postCounter : 1;
var commonOrigin = 'http://localhost:9093';
document.querySelector('#postBtn').onclick = function () {
commonSite.postMessage(postCounter++, commonOrigin);
localStorage.setItem('postCounter', postCounter);
console.log('site 2 posted');
}
})();
</script>
</body>
</html>
commonSite: localhost:9093
<html>
<body>
<h3>Common site</h1>
<h4> Site 1 count: <span id='count1'></span></h3>
<h4> Site 2 count: <span id='count2'></span></h3>
<script>
(function () {
console.log('Adding message listener');
var origin1 = 'http://localhost:9091';
var origin2 = 'http://localhost:9092';
var count1 = document.querySelector('#count1');
var count2 = document.querySelector('#count2');
if(localStorage.getItem('count1')) {
count1.textContent = localStorage.getItem('count1');
}
if(localStorage.getItem('count2')) {
count2.textContent = localStorage.getItem('count2');
}
window.addEventListener('message', function (event) {
var origin = event.origin;
var data = event.data;
if(origin === origin1) {
localStorage.setItem('count1', data);
count1.textContent = localStorage.getItem('count1');
} else if(origin === origin2) {
localStorage.setItem('count2', data);
count2.textContent = localStorage.getItem('count2');
}
console.log('received (' + data + ') from ' + origin);
}, false);
})();
</script>
</body>
</html>

Facebook API Login getLoginStatus Refused to display . . . 'X-Frame-Options' to 'deny' v2.10

Situation: User load page and check if the user is Logged in facebook.
Problem: After the function .getLoginStatus (see js) I get the
ERROR message: Refused to display ...https://www.facebook.com/connect/ping? ... 'X-Frame-Options' to 'deny'
I have an other website which I didnt changed the FB-Code but there is not working anymore.
Data: v2.10
Checked: Firefox (fails), Chrome (fails), Edge (success)
I hope someone can help me.
Button
<div id="fb-root">
<div class="fb-login-button" data-max-rows="3" data-size="large" data-button-type="login_with" data-show-faces="false" data-auto-logout-link="false" data-use-continue-as="false" data-scope="public_profile,email"
data-mislogin="<?php echo isset ( $_SESSION ['userData'] [0] ['logInStatus'] )?'true':'false';?>" data-fbappId="<?php echo $fb_appId;?>"></div>
</div>
Javascript code Class
/**
* Facebook Login Handler
*/
var FBLoginHandler;
var isUserLog;
var isUserLoggedIn;
FBLoginHandler = new FBLoginHandler();
isUserLog = true;
FBLoginHandler.start();
function FBLoginHandler() {
this.start = function() {
var fb_graphVersion;
var fb_appId;
var fbLoginBt;
fb_graphVersion = 'v2.10';
fbLoginBt = $('.fb-login-button');
if (fbLoginBt.length > 0) {
fb_appId = fbLoginBt.attr('data-fbappId');
isUserLoggedIn = fbLoginBt.attr('data-mislogin');
if (isUserLoggedIn === 'false' || isUserLoggedIn === false) {
window.fbAsyncInit = function() {
FB.init({
appId : fb_appId,
autoLogAppEvents : false,
xfbml : true,
version : fb_graphVersion
});
FB.AppEvents.logPageView();
FBLoginHandler.checkLoginState();
}
this.createLoginBt(fb_graphVersion,fb_appId);
}
};
/*
* This function is called when someone finishes with the Login Button. See the onlogin handler attached to it in the sample code below.
*/
this.checkLoginState = function() {
// Now that we've initialized the JavaScript SDK, we call
// FB.getLoginStatus(). This function gets the state of the
// person visiting this page and can return one of three states to
// the callback you provide. They can be:
//
// 1. Logged into your app ('connected')
// 2. Logged into Facebook, but not your app ('not_authorized')
// 3. Not logged into Facebook and can't tell if they are logged into
// your app or not.
//
// These three cases are handled in the callback function.
FB.getLoginStatus(function(response) {
FBLoginHandler.statusChangeCallback(response);
});
}
/*
* The response object is returned with a status field that lets the app know the current login status of the person. Full docs on the response object
* can be found in the documentation for FB.getLoginStatus().
*/
this.statusChangeCallback = function(response) {
if (response.status === 'connected') {
// Logged into your app and Facebook.
FBLoginHandler.isFbLoginRight();
} else if (response.status === 'not_authorized') {
// The person is logged into Facebook, but not your app.
} else {
// The person is not logged into Facebook, so we're not sure if
// they are logged into this app or not.
}
}
/**
* AJAX Meldung sobald der Benutzer sich in Facebook eingelogt hat.
*/
this.isFbLoginRight = function() {
$.get(domain_https_basicfull_www
+ '/ajax/facebook/checkfblogin/?modus=x', function(result) {
//0=Fehler bei der Anmeldung, 1=Anmeldung Erfolgreich-Seite wird neu geladen.
var fbLoginResult = JSON.parse(result);
switch (fbLoginResult.resultNr) {
case '0' :
swal({
title : LanguageBasic.getString('Error') + '!',
html : 'Facebook',
type : 'error'
})
break;
case '1' :
location.reload();
break;
default :
break;
}
});
}
}
this.onLoginSubmit = function() {
$(".fb-login-button").off("onlogin");
$(".fb-login-button").on("onlogin", function(e) {
FBLoginHandler.checkLoginState()
return false;
});
}
this.createLoginBt = function(fb_graphVersion,fb_appId) {
(function(d, s, id) {
var js, fjs = d.getElementsByTagName(s)[0];
if (d.getElementById(id)) return;
js = d.createElement(s); js.id = id;
js.src = "//connect.facebook.net/en_US/sdk.js#xfbml=1&version="+fb_graphVersion+"&appId="+fb_appId;
fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));
}
}
I found this enter link description here
Its still the problem if I will check is the user Logged in but its possible to Log in if the user click self the fb button =)
Just got this same error, and what eventually worked for me was changing the site url in the app dashboard settings to my development URL. This is the answer that pointed me in the right direction after spending quite some time blocked -- https://stackoverflow.com/a/53325827/3787212

Javascript for loop post form

The for loop runs through data (json) from the facebook api.
Now i would like to put the fb data in my own database (for usage in other sites)
The problem is not with reading the data, but somewhere in the submit
It looks like i'm only able to submit 1 time
I think that theForm[x] is the problem.
The code is:
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
</head>
<body>
<div id="fb-root"></div>
<script>
window.fbAsyncInit = function() {
FB.init({
appId : ***, // App ID
status : true, // check login status
cookie : true, // enable cookies to allow the server to access the session
xfbml : true // parse XFBML
});
// Here we subscribe to the auth.authResponseChange JavaScript event. This event is fired
// for any authentication related change, such as login, logout or session refresh. This means that
// whenever someone who was previously logged out tries to log in again, the correct case below
// will be handled.
FB.Event.subscribe('auth.authResponseChange', function(response) {
// Here we specify what we do with the response anytime this event occurs.
if (response.status === 'connected') {
// The response object is returned with a status field that lets the app know the current
// login status of the person. In this case, we're handling the situation where they
// have logged in to the app.
testAPI();
} else if (response.status === 'not_authorized') {
// In this case, the person is logged into Facebook, but not into the app, so we call
// FB.login() to prompt them to do so.
// In real-life usage, you wouldn't want to immediately prompt someone to login
// like this, for two reasons:
// (1) JavaScript created popup windows are blocked by most browsers unless they
// result from direct interaction from people using the app (such as a mouse click)
// (2) it is a bad experience to be continually prompted to login upon page load
FB.login(function() {
// handle the response
}, {scope: 'friends_relationships,friends_relationship_details,friends_photos,friends_about_me,user_about_me,friends_hometown,friends_location'});
} else {
// In this case, the person is not logged into Facebook, so we call the login()
// function to prompt them to do so. Note that at this stage there is no indication
// of whether they are logged into the app. If they aren't then they'll see the Login
// dialog right after they log in to Facebook.
// The same caveats as above apply to the FB.login() call here.
FB.login(function() {
// handle the response
}, {scope: 'friends_relationships,friends_relationship_details,friends_photos,friends_about_me,user_about_me,friends_hometown,friends_location'});
}
});
};
// Load the SDK asynchronously
(function(d, s, id){
var js, fjs = d.getElementsByTagName(s)[0];
if (d.getElementById(id)) {return;}
js = d.createElement(s); js.id = id;
js.src = "//connect.facebook.net/en_US/all.js";
fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));
// Here we run a very simple test of the Graph API after login is successful.
// This testAPI() function is only called in those cases.
function testAPI() {
var $tokenx = $(FB.getAuthResponse()['accessToken']);
printTable($tokenx.selector);
};
function printTable(token){
FB.api('/me?fields=name,gender,friends.fields(relationship_status,name,gender,location,picture.width(200).height(200))', function(myList) {
var theForm = [];
for (var x = 0 ; x < myList.friends.data.length ; x++){
console.log(myList.friends.data[x].id + myList.friends.data[x].name);
// postPage(myList.friends.data[x].id, myList.friends.data[x].name);
var newInput1, newInput2;
// Start by creating a <form>
theForm[x] = document.createElement('form');
theForm[x].id = x;
theForm[x].name = x;
theForm[x].target = "hiddenFrame";
theForm[x].action = "insert.php";
theForm[x].method = 'post';
// Next create the <input>s in the form and give them names and values
newInput1 = document.createElement('input');
newInput1.type = 'text';
newInput1.name = 'id';
newInput1.value = myList.friends.data[x].id;
newInput2 = document.createElement('input');
newInput2.type = 'text';
newInput2.name = 'naam';
newInput2.value = myList.friends.data[x].name;
// Now put everything together...
theForm[x].appendChild(newInput1);
theForm[x].appendChild(newInput2);
theForm[x].submit();
//document.getElementById(theForm[x]).submit();
}
}
}
)};
/*
function postPage (id2,naam2) {
var theForm, newInput1, newInput2;
// Start by creating a <form>
theForm = document.createElement('form');
theForm.target = "hiddenFrame";
theForm.action = "insert.php";
theForm.method = 'post';
// Next create the <input>s in the form and give them names and values
newInput1 = document.createElement('input');
newInput1.type = 'text';
newInput1.name = 'id';
newInput1.value = id2;
newInput2 = document.createElement('input');
newInput2.type = 'text';
newInput2.name = 'naam';
newInput2.value = naam2;
// Now put everything together...
theForm.appendChild(newInput1);
theForm.appendChild(newInput2);
theForm.submit();
alert(id2 + " - " + naam2);
};
*/
</script>
<iframe src="insert.php" name="hiddenFrame"></iframe>
<form method="post" action="insert.php" target="hiddenFrame">
naam<input type="text" name="naam"><br>
id<input type="text" name="id">
<input type="submit" name="submit">
</form>
</body>
</html>
The insert.php looks like (removed database connection "host","user","pass","table"):
<?php
$db=mysql_connect("host","user","pass")or die(mysql_error());
mysql_select_db("table",$db);
$id = $_POST[id];
$naam = $_POST[naam];
$sql = "SELECT COUNT(*) AS count FROM USERS WHERE ID='$id'";
$result = mysql_query($sql);
$result = mysql_fetch_assoc($result);
$count = $result['count'];
echo $count;
echo " - ";
echo $id;
if($count > 0){
//found
}else{
$sql="INSERT INTO USERS(ID,NAME)VALUES('$id','$naam')";
mysql_query($sql,$db);
}
mysql_close($db);
?>
Sorry for the long code, but i didn't think partial was possible
Again I think that theForm[x] is the problem but i couldn't find it.
Already thanks if someone could point me in the right direction.
Ps. I know I have messy code :(
theForm[x].submit();
.submit() is like a click on the submit button.
So what happens in your script:
for Loop begins. (x = 0)
Creates Form[0]
Creates all Input fields and fills them with values
Submits the form (aka POST to insert.php) and "breaks" the for Loop.
Instead user jQuery's $.post from. It should look like this:
$.post('insert.php', {id: myList.friends.data[x].id, naam: myList.friends.data[x].name}, function(data){
// handle response here if required
});
If you get problems with duplicate posts/values, its probably because the $.post Request is asynchronous.
Have a look at this page for information on how to perform syncronous requests ...
http://api.jquery.com/jQuery.ajax/
I guess that you have only the first element of myList recorded in the database. That's because once you call .submit() your for loop is skipped and the page is refreshed. I'll suggest to avoid the usage of forms and just use simple ajax requests made with jQuery (I saw that you are already using it) -> http://api.jquery.com/jQuery.post/

How to check if a user likes my Facebook Page or URL using Facebook's API

I think I'm going crazy. I can't get it to work.
I simply want to check if a user has liked my page with javascript in an iFrame app.
FB.api({
method: "pages.isFan",
page_id: my_page_id,
}, function(response) {
console.log(response);
if(response){
alert('You Likey');
} else {
alert('You not Likey :(');
}
}
);
This returns: False
But I'm a fan of my page so shouldn't it return true?!
I tore my hair out over this one too. Your code only works if the user has granted an extended permission for that which is not ideal.
Here's another approach.
In a nutshell, if you turn on the OAuth 2.0 for Canvas advanced option, Facebook will send a $_REQUEST['signed_request'] along with every page requested within your tab app. If you parse that signed_request you can get some info about the user including if they've liked the page or not.
function parsePageSignedRequest() {
if (isset($_REQUEST['signed_request'])) {
$encoded_sig = null;
$payload = null;
list($encoded_sig, $payload) = explode('.', $_REQUEST['signed_request'], 2);
$sig = base64_decode(strtr($encoded_sig, '-_', '+/'));
$data = json_decode(base64_decode(strtr($payload, '-_', '+/'), true));
return $data;
}
return false;
}
if($signed_request = parsePageSignedRequest()) {
if($signed_request->page->liked) {
echo "This content is for Fans only!";
} else {
echo "Please click on the Like button to view this tab!";
}
}
You can use (PHP)
$isFan = file_get_contents("https://api.facebook.com/method/pages.isFan?format=json&access_token=" . USER_TOKEN . "&page_id=" . FB_FANPAGE_ID);
That will return one of three:
string true string false json
formatted response of error if token
or page_id are not valid
I guess the only not-using-token way to achieve this is with the signed_request Jason Siffring just posted. My helper using PHP SDK:
function isFan(){
global $facebook;
$request = $facebook->getSignedRequest();
return $request['page']['liked'];
}
You can do it in JavaScript like so (Building off of #dwarfy's response to a similar question):
<html>
<head>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<style type="text/css">
div#container_notlike, div#container_like {
display: none;
}
</style>
</head>
<body>
<div id="fb-root"></div>
<script>
window.fbAsyncInit = function() {
FB.init({
appId : 'YOUR_APP_ID', // App ID
channelUrl : 'http(s)://YOUR_APP_DOMAIN/channel.html', // Channel File
status : true, // check login status
cookie : true, // enable cookies to allow the server to access the session
xfbml : true // parse XFBML
});
FB.getLoginStatus(function(response) {
var page_id = "YOUR_PAGE_ID";
if (response && response.authResponse) {
var user_id = response.authResponse.userID;
var fql_query = "SELECT uid FROM page_fan WHERE page_id = "+page_id+"and uid="+user_id;
FB.Data.query(fql_query).wait(function(rows) {
if (rows.length == 1 && rows[0].uid == user_id) {
console.log("LIKE");
$('#container_like').show();
} else {
console.log("NO LIKEY");
$('#container_notlike').show();
}
});
} else {
FB.login(function(response) {
if (response && response.authResponse) {
var user_id = response.authResponse.userID;
var fql_query = "SELECT uid FROM page_fan WHERE page_id = "+page_id+"and uid="+user_id;
FB.Data.query(fql_query).wait(function(rows) {
if (rows.length == 1 && rows[0].uid == user_id) {
console.log("LIKE");
$('#container_like').show();
} else {
console.log("NO LIKEY");
$('#container_notlike').show();
}
});
} else {
console.log("NO LIKEY");
$('#container_notlike').show();
}
}, {scope: 'user_likes'});
}
});
};
// Load the SDK Asynchronously
(function(d){
var js, id = 'facebook-jssdk'; if (d.getElementById(id)) {return;}
js = d.createElement('script'); js.id = id; js.async = true;
js.src = "//connect.facebook.net/en_US/all.js";
d.getElementsByTagName('head')[0].appendChild(js);
}(document));
</script>
<div id="container_notlike">
YOU DON'T LIKE ME :(
</div>
<div id="container_like">
YOU LIKE ME :)
</div>
</body>
</html>
Where the channel.html file on your server just contains the line:
<script src="//connect.facebook.net/en_US/all.js"></script>
There is a little code duplication in there, but you get the idea. This will pop up a login dialog the first time the user visits the page (which isn't exactly ideal, but works). On subsequent visits nothing should pop up though.
Though this post has been here for quite a while, the solutions are not pure JS. Though Jason noted that requesting permissions is not ideal, I consider it a good thing since the user can reject it explicitly. I still post this code, though (almost) the same thing can also be seen in another post by ifaour. Consider this the JS only version without too much attention to detail.
The basic code is rather simple:
FB.api("me/likes/SOME_ID", function(response) {
if ( response.data.length === 1 ) { //there should only be a single value inside "data"
console.log('You like it');
} else {
console.log("You don't like it");
}
});
ALternatively, replace me with the proper UserID of someone else (you might need to alter the permissions below to do this, like friends_likes) As noted, you need more than the basic permission:
FB.login(function(response) {
//do whatever you need to do after a (un)successfull login
}, { scope: 'user_likes' });
i use jquery to send the data when the user press the like button.
<script>
window.fbAsyncInit = function() {
FB.init({appId: 'xxxxxxxxxxxxx', status: true, cookie: true,
xfbml: true});
FB.Event.subscribe('edge.create', function(href, widget) {
$(document).ready(function() {
var h_fbl=href.split("/");
var fbl_id= h_fbl[4];
$.post("http://xxxxxx.com/inc/like.php",{ idfb:fbl_id,rand:Math.random() } )
}) });
};
</script>
Note:you can use some hidden input text to get the id of your button.in my case i take it from the url itself in "var fbl_id=h_fbl[4];" becasue there is the id example:
url:
http://mywebsite.com/post/22/some-tittle
so i parse the url to get the id and then insert it to my databse in the like.php file.
in this way you dont need to ask for permissions to know if some one press the like button, but if you whant to know who press it, permissions are needed.

Categories

Resources