• 0

Hide Facebook divs if Facebook is blocked


Go to solution Solved by Seahorsepip,

Question

wrack

Hi,

 

I am working on a small site http://www.hagglehive.com and I want to use Facebook follow, like, share & comments plugin. http://www.hagglehive.com/en-au/Haggle/Detail/Lumia-930-Green-4G-Lte-32Gb-On-25-Aug-2014-Price-549-221 page has all of those plugin added.

 

I am using ASP.NET with .NET Framework 4.5. Below is the code at the bottom of the master page. 

<!-- Facebook Scripts -->
<div id="fb-root"></div>
<script>
	(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 = "http://connect.facebook.net/en_US/sdk.js#xfbml=1&version=v2.0";
		fjs.parentNode.insertBefore(js, fjs);
	}(document, 'script', 'facebook-jssdk'));
</script>

Below is one of the div where follow button should show up. 

<div runat="server" id="divFacebookFollowButton" class="fb-follow RoundBorder FacebookFollowButton" data-href="//www.facebook.com/HaggleHive" data-width="100%" data-colorscheme="light" data-layout="standard" data-show-faces="false"></div>

What I want to do is, hiding all Facebook related DIVs first and then using jQuery Ajax, I am trying to connect to Facebook and see if the result is a success. If so then I make them all visible. This is the part I am struggling with.

$(document).ready(function () {
    // Hide facebook divs first
    //$(".fb-follow").hide();
    //$(".fb-like").hide();
    //$(".fb-comments").hide();
    // Check if facebook is blocked
    setTimeout("ShowFacebookIfAvailable();;", 2500);
});

In the above call, I have commented out the part where it hides all divs first. So it is all working now and you can see Facebook div at the top but if I uncomment them then nothing shows up.

 

Below is the function "ShowFacebookIfAvailable".

function ShowFacebookIfAvailable() {
    window.jQuery.support.cors = true;

    $.ajax({
        type: 'HEAD',
        url: 'https://www.facebook.com',
        crossDomain: true,
        success: function (data, textStatus, jqXHR) {
            $(".fb-follow").show();
            $(".fb-like").show();
            $(".fb-comments").show();
        },
        error: function (jqXHR, textStatus, errorThrown) {
        }
    });
}

Any help would be good as I am stuck here.

 

BONUS : What I would ideally like is, first check if Facebook is blocked and only load the JS if not blocked, saving a little download and improving the performance a little. Not sure how to do this though!

 

Cheers :)

Link to post
Share on other sites

9 answers to this question

Recommended Posts

  • 0
Seahorsepip

kinda simpler method:

$(function() {
    var fb = new Image();
    fb.onload = function () {
        //facebook isn't blocked
    }
    fb.onerror = function () {
        //facebook is blocked
    }
    fb.src = "http://facebook.com/favicon.ico";
});

This code actually does not require jQuery but I used it anyway since I'm too lazy to write the js equivalent of $(document).ready

Link to post
Share on other sites
  • 0
wrack

This code actually does not require jQuery but I used it anyway since I'm too lazy to write the js equivalent of $(document).ready

 

Thanks :). That works a treat. Appreciate it.

 

One quick question. I see you used "var fb = new Image(); " to retrieve an image (icon). What type of variable to use if one were to check if a JavaScript can be accessed instead of an image?

Link to post
Share on other sites
  • 0
Seahorsepip

Thanks :). That works a treat. Appreciate it.

One quick question. I see you used "var fb = new Image(); " to retrieve an image (icon). What type of variable to use if one were to check if a JavaScript can be accessed instead of an image?

You can try the following code.

Though it might be a problem with domains that block requests from other servers like facebook for certain files and pages(as example you cant put facebook into a iframe on a website).

$(function() {
    var url = "http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js";
    var jsfile = new XMLHttpRequest();
    jsfile.onerror = function() {
        alert("blocked");
    };
    jsfile.onload = function() {
        alert("available");
    };
    jsfile.open("GET",url);
    jsfile.send();
});
 
Link to post
Share on other sites
  • 0
wrack

You can try the following code.

Though it might be a problem with domains that block requests from other servers like facebook for certain files and pages(as example you cant put facebook into a iframe on a website).

 

Yeah that makes sense to block certain things. I was asking this to do the same thing for the Google Ad as well as Google Analytics. Try to get the JS and if good then load the rest of the script.

 

So here is 1 more question (hopefully final and I hope you don't mind). Let's say it was successful in getting the file so I get into the onload function. How do I then use that object to inject into the webpage rather then reloading it again?

Link to post
Share on other sites
  • 0
wrack

Ahh never mind. Found it. I can do eval(). Looks like this can open my code up to xss attacks. Not going to do it for now then.

 

Thanks for all your help mate.

  • Like 1
Link to post
Share on other sites
  • 0
Seahorsepip

Ahh never mind. Found it. I can do eval(). Looks like this can open my code up to xss attacks. Not going to do it for now then.

 

Thanks for all your help mate.

Never load code from untrusted domains and always make sure to load them trough https to prevent js xss attacks on your users.

Link to post
Share on other sites
  • 0
wrack

That's true. I was going to load google analytics so hopefully it would be safe but you never know with crafty peoples.

Link to post
Share on other sites
  • 0
Seahorsepip

That's true. I was going to load google analytics so hopefully it would be safe but you never know with crafty peoples.

As long you get the analystics js from the official https source and not from a suspicious mirror it shouldn't be a problem. When you use https instead of http it's no longer possible to do any man in the middle attacks, given that the website and it's certificate can be trusted. But the website itself that is serving the js can still be hacked though in case of google analystics I'd more worried about the fact that google is hacked then the malicious js that is being served to your website.

 

So simply said, if you load official js libraries from facebook, google, yahoo, microsoft etc It should be fine as long you use a https url. Also malicious js should never be able to harm your website itself, it should only be able to harm your visitors by showing ads as example.

Link to post
Share on other sites
  • 0
wrack

Thanks. I will use https then.

Link to post
Share on other sites
This topic is now closed to further replies.
  • Recently Browsing   0 members

    No registered users viewing this page.

  • Similar Content

    • By zikalify
      Facebook improves photo descriptions for the visually impaired
      by Paul Hill

      Facebook has announced that it has improved its automatic alternative text (AAT) feature. AAT was introduced in 2016 as a way to generate alternative text on photos to help the visually impaired understand what was going on in the picture, with today’s update the feature can detect the content of images ten times more reliably and provide better information.

      According to the social network, the boost in concepts and improvements in reliability mean that AAT can provide information on more pictures. Facebook said that it can detect activities, landmarks, types of animals and more – an example description generated by AAT could read “May be a selfie of 2 people, outdoors, the Leaning Tower of Pisa.”

      In the previous iteration of AAT, if you uploaded a picture of two friends having their photos taken and people in the background were passing by, AAT would generate a message saying “May be an image of five people” as it included those in the background; the new iteration is more intelligent and incorporates positional location and the relative size of elements. The new system would say there are two people in the centre of the photo and others scattered towards the fringes of the image.

      Artificial intelligence has been introducing great benefits for those that are visually impaired in recent years. When internet connections were slow, alt text was frequently used as a back-up against photos not loading, the alt text could be used by screen readers to tell visually impaired people what the image was showing. As connections got faster, alt text wasn’t used as much but artificial intelligence tools like AAT are now able to fill the gap and provide good descriptions of what’s shown in a shot.

    • By zikalify
      Indian government asks WhatsApp to backtrack on privacy policy
      by Paul Hill



      According to a report from Reuters, India’s Ministry of Electronics and Information Technology asked WhatsApp to backtrack on its planned privacy policy changes which saw it lose users to rivals Telegram and Signal. In a letter, the government complained to WhatsApp saying it was unfair that European users won’t be affected by the changes but Indians will.

      WhatsApp's planned changes have also attracted the attention of Turkish authorities which have launched an antitrust probe. In response to the criticism, WhatsApp delayed the enforcement of its new terms by three months so they won’t be enacted until May 15; ultimately, this will give India more time to pressure the firm over the planned changes.

      According to Reuters, the Ministry, writing to WhatsApp head Will Cathcart, said:

      Accompanying the letter are several questions that India’s IT ministry would like WhatsApp to answer, they ask about which categories of data WhatsApp collects from Indian users, the permissions sought by WhatsApp and the utility of each of these permissions, whether WhatsApp captures information about other running apps, what user profiling goes on and how WhatsApp’s privacy policies differ from country to country.

      WhatsApp has not provided comments to the media about the changes but it previously said the policy wouldn’t affect the privacy of users’ messages with personal contacts. Reuters reports that WhatsApp is running an advertising campaign in India to help quell people’s fears and keep them using the app.

      Source: Reuters

    • By zikalify
      Hungary could copy Poland in sanctioning social media firms
      by Paul Hill



      Hungarian Justice Minister Judit Varga took to Facebook earlier today to announce that she will be consulting with the Hungarian Competition Authority about sanctioning social media firms that engage in ‘unfair commercial practices’. She named Facebook as a firm that tries to reduce the reach of Christian, conservative, and right-wing opinions and that she has personal experience of her posts being "shadow banned".

      Her announcement to go after social media firms comes just days after the Polish government said it was looking to introduce a free speech social media law that would create a free speech council that could issue fines to social media firms if they delete content or ban users who do not break Polish laws.

      Aside from meeting with the Hungarian Competition Authority, Varga also convened a meeting of the country’s Digital Freedom Committee to look into the issue. She said that the committee also works at the EU level to help regulate global tech companies. Both Hungary and Poland have said that this issue must be tackled by the EU but are working for national solutions in the meantime.

      It’s unclear how much support other EU countries would provide to such proposals but German Chancellor Angela Merkel previously stated that Donald Trump’s ban from Twitter was problematic so Poland and Hungary may find some support there.

      Source: Judit Varga (Facebook) via Reuters

    • By News Staff
      Save almost $4K off this 2021 Premium Learn to Code Certification Bundle
      by Steven Parker

      Today's highlighted deal comes via our Online Courses section of the Neowin Deals store, where for only a limited time, you can save 98% off this Premium Learn to Code 2021 Certification Bundle. Amp up your programming skill set with 270+ hours of content on the leading coding languages — taught by top-rated instructors Ft. Rob Percival, Nick Walter, and more!.



      This deal consists of the following courses:

      JavaScript Beginner Bootcamp
      Understand the JavaScript Language & Learn to Create and Launch Interactive Webpages SwiftUI Apps for All Apple Platforms
      Learn the True Magic of SwiftUI & Make Apps and Widgets for iPhone, Mac, iPad, Apple Watch, and AppleTV The Complete C# Programming Course
      Master C# & .NET Framework with Code Challenges, Exercises, & Real-Life Examples The Complete Web Developer Course 2.0
      Learn By Doing: Build 25 Websites & Mobile Apps Alongside Top-Rated Online Coding Instructor, Rob Percival! SwiftUI: The Complete Developer Course
      Learn Everything You Need to Know About the SwiftUI Framework & Leverage All of Its Great New Technologies 2020 Complete Ruby on Rails 6 Bootcamp
      Start From the Basics of Ruby on Rails & Go All the Way to Creating Your Own Applications Learn Python for Data Analysis & Visualization
      Gear Yourself with Necessary Skills for Expert-Proven Data Science Techniques Raspberry Pi Essentials & Extras
      Broaden Your Raspberry Pi's Horizons with This 1-Hour Crash Course PHP & MySQL: Certification Course for Beginners
      Learn to Build Database-Driven Web Applications Using PHP & MySQL Bootstrap & jQuery: Certification Course for Beginners
      Create Fully Animated, Interactive, Mobile Responsive Web Pages Using Bootstrap & jQuery Library HTML, CSS, & JavaScript: Certification Course for Beginners
      A Comprehensive Guide for Beginners Interested in Learning HTML, CSS, & JavaScript to Build Interactive Web Pages Java Foundations
      Master the General Purpose & Object-Oriented Language of Java to Enhance Your Skills for Mobile Development Making APIs with Django & Python
      Use the REST Framework to Quickly Make APIs for Your Django Projects Making Websites with Python & Django 3: The Ultimate Beginner's Guide
      Boot Up the Django 3 Web Framework Written In Python & Develop Websites Fast JavaScript Master Class
      A Comprehensive Course Just About Every Fact on JavaScript You Could Ever Hope to Know Python for Everyone
      Learn the Basic Syntax of How Python Language Works How to Get a Job as a Web Developer
      Tips, Tricks & Industry Secrets to Help You Land That Web Development Job The Python Mega Course: Build 10 Real World Applications
      A Complete Practical Python Course for Beginners & Intermediates! Master Python 3 by Building Actual Python Apps ROS2 For Beginners
      Master the Key ROS Concepts to Create Powerful & Scalable Robot Applications The Complete Web Developer Course: Build 20 Websites
      Learn the Fundamentals of HTML, CSS & JavaScript by Building 20 Real-World Websites Machine Learning for Absolute Beginners
      Learn to Build Machine Learning Models Using Spreadsheet Data Java Interview Questions: Data Structures & Algorithms
      The Best Java Interview Guide with the Most Common Beginner Questions Asked by FANG Companies

      The Ultimate Amazon Honeycode Guide: Build 7 Apps
      Build Apps to Automate Data Entry: Make Inventory Management Apps & More Easy Business Projects

      Learn Flutter & Dart: Complete App Development Projects
      Build Apps in Flutter, Google's Cross-Platform Framework & Code with Its Dart Programming Language

      Complete Data Science Training with Python for Data Analysis
      Learn Statistics, Visualization, Machine Learning & More

      C++ Programming for Beginners
      Master C++, An In-Demand, High-End Language Used for Programs, Games, Development Libraries, & More

      The Complete Front-End Web Development Course
      Take a Hands-on Approach to Learning Real Programming Skills

      Good to know
      Certification of completion included Length of time users can access this course: lifetime Redemption deadline: redeem your code within 30 days of purchase For a full description, specs, and instructor info, click here.

      Here's the deal:
      This Premium Learn to Code 2021 Certification Bundle normally costs* $4,056, but you can pick it up for just $59.99 for a limited time - that represents a saving of $3,996.01 (98%) off.

      >> Get this deal, or learn more about it <<
      See all discounted Online Courses. This is a time-limited offer.
      Get $1 credit for every $25 spent · Give $10, Get $10 · 10% off for first-time buyers.

      Not for you?
      If this offer doesn't interest you, why not check out the following offers:



      The Win Your Dream 2020 Tesla Model 3 Giveaway Ivacy VPN - 5 year subscription for just $0.99 per month NordVPN - 2 year subscription at up to 68% off +3 months for free! Private Internet Access VPN - subscriptions at up to 71% off Unlocator VPN or SmartDNS - unblock Geoblock with 7-day free trial Subscribe to Neowin - for $14 a year, or $28 a year for Ad-Free experience Disable Sponsored posts · Neowin Deals · Free eBooks · Neowin Store

      Disclosure: This is a StackCommerce deal or giveaway in partnership with Neowin; an account at StackCommerce is required to participate in any deals or giveaways. For a full description of StackCommerce's privacy guidelines, go here. Neowin benefits from shared revenue of each sale made through our branded deals site, and it all goes toward the running costs.

    • By zikalify
      Polish government eyeing free speech social media law
      by Paul Hill



      According to a report from BBC News, the Polish government has proposed a new law that would fight so-called political correctness online and promote free speech. The new law, if passed, would establish a free speech council that would attempt to stop social media firms from deleting content or banning users who do not contravene Polish laws.

      Any company that was found to be blocking users or deleting their content would be subject to a 50 million zloty ($13.4 million) fine if the content didn’t violate Polish laws. The proposal was announced by the Polish Justice Minister Zbigniew Ziobro on Friday, less than a week after the government’s ideological ally, U.S. President Donald Trump was finally banned from Twitter after years of incendiary use of the platform.

      The free speech council would consist of experts, not politicians, who have been appointed for six-year terms by a three-fifths majority vote in the nation’s parliament. Commenting on the law, Justice Minister Ziobro said:

      The Polish prime minister Mateusz Morawiecki is also in support of the law stating that freedom of speech online is a priority for him and has spoken out against political correctness. According to reports, the prime minister is planning to lobby the European Union to regulate online censorship as he believes domestic regulations may be ineffective without the continent’s support.

      It’s too early to tell if his attempts will be a success or not but German Chancellor Angela Merkel said President Trump’s ban from Twitter was problematic so the Polish government’s ideas may get some support from other leaders.

      Source: BBC News