How to use pure JavaScript to determine whether Facebook/Twitter is blocked? - javascript

Some countries like China is blocking Facebook/Twitter. How to use JavaScript to check whether a website is not accessible?
update:
I am adding a "Share to Facebook" button on a web page. 50% of the visitors are from China and 50% are from outside of China.
For those China visitors, they would never see that Facebook button because it's blocked. I want to use $.hide() or $.empty() to remove the related HTML if I detected that Facebook is blocked. How can I do that?

You can check if loading the facebook SDK is blocked in china (//connect.facebook.net/en_UK/all.js)
If this is the case then you could do something like this:
$.getScript('//connect.facebook.net/en_UK/all.js')
.success(function(){
// do something if facebook is available
});
You need to take care because you need to define a timeout if you want to make a callback for the fail case. I need to check the correct settings later, but currently i don't have time to.
EDIT
Based on the comment of funkybro it would be better to do a JSONP request. Loading the API would inject a butch of code you probably don't need.
So just request e.g.:
$.getJSON('https://graph.facebook.com/feed?callback=?')
.success(function(){
// do something if facebook is available
});
The request will include a failure code because you don't provide at graph node, but knowing that you get an error message from facebook means that it is reachable for the client.

Use jQuery.get like this:
$.get("http://facebook.com").fail(function() {
$(...).hide()
}).done(function() {
$(...).show()
})
Note that this is a cross-site request that will fail for security reasons unless you disable that browser feature.
If that's not possible for you, I suggest you use GeoIP or similar technologies to determine the users origin.

Related

Can you re-"init" a Facebook pixel with different dataProcessing options?

With the advent of the California Consumer Privacy Act (CCPA), it's been necessary for some of our clients to implement Limited Data Usage (LDU) policies for Facebook. Our accepted practice has been to explicitly disable LDU fbq('dataProcessingOptions', []) until a user opts out (via a consent plugin). Here's the crux of my problem. Once a user opts out, I'd like to re-initialize the Facebook pixel with LDU enabled fbq('dataProcessingOptions', ['LDU'], 0, 0) so that future events on the page are processed using the LDU policies. Is it possible to simply call fbq('init', '{pixel_id}') a second time and have this "flag" set?
The Google Chrome Facebook Pixel extension will show what is sent for each event.
I was hoping that maybe sending something like fbq('trackCustom', 'optOut') might trigger it to re-send updated dataProcessing options, but it doesn't seem to.
Facebook is shooting everyone in the foot by not making this process clearer - it should absolutely be possible to wipe out data collected for the session and that's clearly the best way to do it.
I've spent all weekend trying to do this correctly from both technical and legal stand point and it's just a nightmare. CCPA is supposed to be opt-out!
This doesn't work:
// CCPA Notice. We allow California users to opt-out from Facebook's data collection by means
// of our 'Do not sell my information' link at the bottom of our website. Please use this link
// to trigger an opt-out via Facebook's API. Questions: privacy at example.com
fbq('dataProcessingOptions', []);
fbq('init', account_id);
fbq('track', 'PageView');
optOut()
{
fbq('dataProcessingOptions', ['LDO'], 1, 1000);
fbq('trackCustom', 'registerOptOut');
}
I'd recommend putting some text here because people are out to get us by finding vulnerable websites and this makes it look like I know what I'm doing.

sharePoint online count unread message from office365

As part of a project whose aim is to notably improve the visual side of a SharePoint Online site, I'm a bit stuck. On the home page in the left banner, users want to see the number of unread messages they have in Office365.
I created an area in the master page to put the result in. I thought the Rest API used to do this :
$.ajax ({
type: "GET",
url: " https://outlook.office365.com/ews/odata/Me/Folders/Inbox",
dataType : "json",
success : function (resp) {
// count unread messages
},
error : function (e) {
alert (' Error121212 :' + JSON.stringify (e));
}
})
Unfortunately I get an error like cross domain. I tried with JSONP but it does not work either (uncaught syntax error unexpected token).
Can you please tell me if this is a good practice? I feel that it anyways I must find a technic for authentication. (In the case of JSONP I have a popup that asks me authentication and then problem occurs on callback apparently)...
I want to avoid developing a type requiring a typical deployment Wsp...
Thank you in advance for your help.
Your URL for the ajax request seems incorrect. The URL for getting the inbox messages via the API is: https://outlook.office365.com/api/v1.0/me/folders/inbox/messages
Once you get the response, you can count the number of objects with the IsRead property set to false using a simple for loop and display that count.
The issue here is related to CORS and how browsers refuse to handle cross-domain requests. To get around this, typically you would either
Change the response header on the remote server - not an option here
Use some sort of proxy to handle the requests - here's where SharePoint apps come in.
I know you stipulated that you want to avoid using a WSP style deployment but there simply isn't a way around it, you have to use the SharePoint App Model
This article goes a long way to answer your question, but for completion the basic steps are as follows
Create a SharePoint hosted app in Visual Studio
In the App Manifest, you need to define the trust relationship with the remote host (in this case the host of outlook.office365.com) using the AppManifest section
Use SP.RequestExecutor.executor to make the request on your behalf

Hide a javascript if user comes from an specific location

I want a javascript file (<script src=" file here " >) to be hidden if a user lets say comes from China.
How can i do it?
I'm Chinese and I reserve all my rights to protest. :)
Actually you have a few options, you can do it front-end or back-end.
Front-end solution
Use HTML5 Geolocation to determine the longitude and latitude of current user and check whether it's within China or not(don't forget to contain Taiwan). The defect is only modern browsers are supported, you should probably set up plan B.
//jQuery, ip-api is a RESTful service, do it in front-end
$.getJSON('http://ip-api.com/json/?callback=?', function(response){
alert(response.country);
if(response.country === "China"){
$.getScript("script_for_Chinese.js");
}
});
Back-end solution
Check the user IP and find out if it's from China(there are a bunch of IP to location RESTful services)
Check HTTP header if the Accept-Language part contains string like zh-CN or zh-TW. This may also hurt the people using Chinese in other countries.
As for example requested, I won't recommend you use front-end solution or IP-to-location back-end solution. The only one that might work is based on http header.
//PHP, if the client accept Chinese, assume he is from China
if(preg_match('/(zh-CN|zh-TW|zh)/i', $_SERVER['HTTP_ACCEPT_LANGUAGE'])){
echo '<script src="script_for_Chinese.js" type="text/javascript"></script>';
}
You can try using a geolocation service but considering that you can defeat that by using a proxy (like a hacked machine in the US) somewhere else or by spoofing the request to look like it came from given location it may not do you much good in the end.

Google OAuth WildCard Domains

I am using the google auth but keep getting an origin mismatch. The project I am working has sub domains that are generated by the user. So for example there can be:
john.example.com
henry.example.com
larry.example.com
In my app settings I have one of my origins being http://*.example.com but I get an origin mismatch. Is there a way to solve this? Btw my code looks like this:
gapi.auth.authorize({
client_id : 'xxxxx.apps.googleusercontent.com',
scope : ['https://www.googleapis.com/auth/plus.me',
state: 'http://henry.example.com',
'https://www.googleapis.com/auth/userinfo.email', 'https://www.googleapis.com/auth/userinfo.profile'],
immediate : false
}, function(result) {
if (result != null) {
gapi.client.load('oath2', 'v2', function() {
console.log(gapi.client);
gapi.client.oauth2.userinfo.get().execute(function(resp) {
console.log(resp);
});
});
}
});
Hooray for useful yet unnecessary workarounds (thanks for complicating yourself into a corner Google)....
I was using Google Drive using the javascript api to open up the file picker, retrieve the file info/url and then download it using curl to my server. Once I finally realized that all my wildcard domains would have to be registered, I about had a stroke.
What I do now is the following (this is my use case, cater it to yours as you need to)
On the page that you are on, create an onclick event to open up a new window in a specific domain (https://googledrive.example.com/oauth/index.php?unique_token={some unique token}).
On the new popup I did all my google drive authentication, had a button to click which opened the file picker, then retrieved at least the metadata that I needed from the file. Then I stored the token (primary key), access_token, downloadurl and filename in my database (MySQL).
Back on step one's page, I created a setTimeout() loop that would run an ajax call every second with that same unique_token to check when it had been entered in the database. Once it finds it, I kill the loop and then retrieve the contents and do with them as I will (in this case I uploaded them through a separate upload script that uses curl to fetch the file).
This is obviously not the best method for handling this, but it's better than entering each and every subdomain into googles cloud console. I bet you can probably do this with googles server side oauth libraries they use, but my use case was a little complicated and I was cranky cause I was frustrated at the past 4 days I've spent on a silly little integration with google.
Wildcard origins are not supported, same for redirect URIs.
The fact that you can register a wildcard origin is a bug.
You can use the state parameter, but be very careful with that, make sure you don't create an open redirector (an endpoint that can redirect to any arbitrary URL).

FB.login() response is inconsistent

Most people who are trying to login with Facebook are having no trouble, but about 5% of people who try to sign up are unable to. I believe the issue is due to some people not having certain information in the response that I get back from Facebook. Why do some people not have email and location in their response even if I have requested the email and user_location permissions?
I looked at your javascript and saw a couple of things you should check into:
When you initialize the javascript SDK you set cookie=false and status=false. Most examples I've seen set these to true. This might not have anything to do with the 5% exceptions you are seeing, but I don't see how it would hurt to set them to true, and it might help. Give it a try and see if it makes a difference.
The bigger issue I see is your code is assuming that the permissions are granted. You really need to check the response object in the callback to FB.login. The user might not have logged in, and they might have denied some of the permissions. You need to check the response object to see if it has an error in it.
You will need to query the permissions table (fql) or do a get to /me/permissions to know what permissions they granted. It would be nice if the FB.login callback response object told you what was granted vs. denied, but it doesn't.
Also I believe there are cases where people don't have an email registered with Facebook or a location.
To summarize: you cannot trust that you will get what you ask for, you need to check the response object and handle the exceptions gracefully, reprompting for authentication with a message indicating why you are re-prompting.
Another thing you might want to consider adding is a client-side logging tool such as log4javascript (or roll your own) that gathers more information about these exceptions. There may be a pattern for example a specific browser that is not handling things well.

Categories

Resources