Blog

Posting a HTML5 Canvas image to Facebook and Twitter

by Jerez Bain on February 17, 2016 77 comments

Update #1 – June 8, 2019

Due to changes to their API, Canvas image sharing to Facebook is not possible at this time.


Part of a recent project was to take an HTML 5 Canvas Image and post it to Facebook and Twitter. Although this sounds pretty straightforward, the challenge was that there would be no image saved to the server. I couldn’t just slap share buttons on the page, because share dialogs expect content that already exists on a server. Using Facebook’s API and Twitter’s API we are able to share rich dynamic content. Here’s a guide on what I did… (PHP, Javascript, jQuery, TwitterOAuth)

Code on Github

Canvas Image

Lets create a simple canvas element and add an image of a panda (we all like pandas, right?).

HTML
<canvas id="canvas" style="border:1px solid black;" width="256" height="256"></canvas>
JavaScript
// Canvas Object
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');

// load image from data url
var imageObj = new Image();
imageObj.onload = function() {
ctx.drawImage(this, 0, 0);
};

imageObj.src = 'panda_dark.png';
Resulting Canvas

Post HTML5 Canvas Image on Facebook and Twitter_panda

Canvas to Base64 to Blob/Binary String to Social Media

In the following steps we will convert the canvas image to base64 by using .toDataURL() which is part of the Canvas API.

HTMLCanvasElement.toDataURL() Returns a data-URL containing a representation of the image in the format specified by the type parameter.

The function below will take the base64 string and convert it to a Blob/Binary String that will be sent to the Facebook and Twitter APIs. This function will be referenced later in the code.

Blob(blobParts[, options]) Returns a newly created Blob object whose content consists of the concatenation of the array of values given in parameter.

function dataURItoBlob(dataURI) {
    var byteString = atob(dataURI.split(',')[1]);
    var ab = new ArrayBuffer(byteString.length);
    var ia = new Uint8Array(ab);
    for (var i = 0; i < byteString.length; i++) {
        ia[i] = byteString.charCodeAt(i);
    }
    return new Blob([ab], {type: 'image/png'});
}

Posting to Facebook

Posting the image to Facebook will require creating a Facebook app which you will also need to request the ‘publish_actions’ permission when making the app live.  Now we create a ‘Post to Facebook’ button and link a click handler for the logic. Below you can see that we grab the base64 encoding of the canvas image that has been returned in the format of a .png image. We then try to convert the base64 string into a Blob. Using the Facebook JS SDK, after the user has logged in and given the app permission, the ‘postImageToFacebook’ function is called and passed several arguments.

$('#shareFB').click(function () {
    var data = $('#canvas')[0].toDataURL("image/png");
    try {
        blob = dataURItoBlob(data);
    } catch (e) {
        console.log(e);
    }
    FB.getLoginStatus(function (response) {
        console.log(response);
        if (response.status === "connected") {
            postImageToFacebook(response.authResponse.accessToken, "Canvas to Facebook/Twitter", "image/png", blob, window.location.href);
        } else if (response.status === "not_authorized") {
            FB.login(function (response) {
                postImageToFacebook(response.authResponse.accessToken, "Canvas to Facebook/Twitter", "image/png", blob, window.location.href);
            }, {scope: "publish_actions"});
        } else {
            FB.login(function (response) {
                postImageToFacebook(response.authResponse.accessToken, "Canvas to Facebook/Twitter", "image/png", blob, window.location.href);
            }, {scope: "publish_actions"});
        }
    });
});

Posting to the blob to facebook requires the use of FormData. The function first uploads the picture to facebook without creating a story on the user’s timeline. Then it retrieves the saved image and creates a story on the user’s timeline using the fields provided.
NOTE: The ‘message’ field must be left blank unless you provide the user a way to add one.

function postImageToFacebook(token, filename, mimeType, imageData, message) {
    var fd = new FormData();
    fd.append("access_token", token);
    fd.append("source", imageData);
    fd.append("no_story", true);

    // Upload image to facebook without story(post to feed)
    $.ajax({
        url: "https://graph.facebook.com/me/photos?access_token=" + token,
        type: "POST",
        data: fd,
        processData: false,
        contentType: false,
        cache: false,
        success: function (data) {
            console.log("success: ", data);

            // Get image source url
            FB.api(
                "/" + data.id + "?fields=images",
                function (response) {
                    if (response && !response.error) {
                        //console.log(response.images[0].source);

                        // Create facebook post using image
                        FB.api(
                            "/me/feed",
                            "POST",
                            {
                                "message": "",
                                "picture": response.images[0].source,
                                "link": window.location.href,
                                "name": 'Look at the cute panda!',
                                "description": message,
                                "privacy": {
                                    value: 'SELF'
                                }
                            },
                            function (response) {
                                if (response && !response.error) {
                                    /* handle the result */
                                    console.log("Posted story to facebook");
                                    console.log(response);
                                }
                            }
                        );
                    }
                }
            );
        },
        error: function (shr, status, data) {
            console.log("error " + data + " Status " + shr.status);
        },
        complete: function (data) {
            //console.log('Post to facebook Complete');
        }
    });
}
Resulting Post to Facebook
Post HTML5 Canvas Image on Facebook and Twitter_panda_fb

Posting to Twitter

Posting the image to twitter will also require you to create a Twitter App. Twitter still uses OAuth 1.0, so you will either need to use server-side code or a service such as ouath.io. Unless requested I’ll skip the authentication process here for TwitterOAuth which I’m using. The functions used below handle the popup that communicates with server-side code Credits to https://github.com/nobuf/jQuery-OAuth-Popup.

// Twitter oauth handler
$.oauthpopup = function (options) {
    if (!options || !options.path) {
        throw new Error("options.path must not be empty");
    }
    options = $.extend({
        windowName: 'ConnectWithOAuth' // should not include space for IE
        , windowOptions: 'location=0,status=0,width=800,height=400'
        , callback: function () {
            debugger;
            //window.location.reload();
        }
    }, options);

    var oauthWindow = window.open(options.path, options.windowName, options.windowOptions);
    var oauthInterval = window.setInterval(function () {
        if (oauthWindow.closed) {
            window.clearInterval(oauthInterval);
            options.callback();
        }
    }, 1000);
};
// END Twitter oauth handler

//bind to element and pop oauth when clicked
$.fn.oauthpopup = function (options) {
    $this = $(this);
    $this.click($.oauthpopup.bind(this, options));
};

Posting to Twitter is similar to Facebook in the case that you use FormData, but this is sent to your server-side handler or service instead. You can send the image as a Blob but this is not necessary. The variable window.twit contains authentication data sent from the popup window back to the parent webpage/tab.

$('#shareTW').click(function () {
    var dataURL = $('#canvas')[0].toDataURL("image/png");
    $.oauthpopup({
        path: '/auth/twitter.php',
        callback: function () {
            console.log(window.twit);
            var data = new FormData();
            // Tweet text
            data.append('status', "Look at the cute panda! " + window.location.href + " @jerezb31");
            // Binary image
            data.append('image', dataURL);
            // oAuth Data
            data.append('oauth_token', window.twit.oauth_token);
            data.append('oauth_token_secret', window.twit.oauth_token_secret);
            // Post to Twitter as an update with

            return $.ajax({
                url: '/auth/share-on-twitter.php',
                type: 'POST',
                data: data,
                cache: false,
                processData: false,
                contentType: false,
                success: function (data) {
                    console.log('Posted to Twitter.');
                    console.log(data);
                }
            });
        }
    });
});

Here is the snippet of server-side code that handles the FormData to be sent to twitter using TwitterOAuth. The credentials are verified then the base64 image is uploaded to Twitter’s API ‘upload/image’ endpoint. The object returned is then added to the list of parameters for posting a status.

// '/auth/share-on-twitter.php'

require_once '../vendor/abraham/twitteroauth/autoload.php';
use Abraham\TwitterOAuth\TwitterOAuth;

session_start();

define('CONSUMER_KEY', '*************');
define('CONSUMER_SECRET', '************');
define('OAUTH_CALLBACK', '*****************');

//echo '<pre>'.print_r($_REQUEST).'</pre>';
//exit;

$connection = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET, $_REQUEST['oauth_token'], $_REQUEST['oauth_token_secret']);
$twitterUser = $connection->get("account/verify_credentials");

$media1 = $connection->upload('media/upload', ['media' => $_REQUEST['image']]);
$parameters = [
    'status' => $_REQUEST['status'],
    'media_ids' => implode(',', [$media1->media_id_string]),
];
$result = $connection->post('statuses/update', $parameters);
echo json_encode($result);
Resulting post to Twitter

Post HTML5 Canvas Image on Facebook and Twitter_panda_tw

View the working Demo!

Code on Github

Jerez BainPosting a HTML5 Canvas image to Facebook and Twitter

77 comments

Join the conversation
  • KOJO AMAKYE - September 26, 2016 reply

    I wonder what I’m doing wrong. This is not working for me

    Jerez Bain - October 5, 2016 reply

    Hi Kojo, did you try the code on github? https://github.com/giovanniorigins/HTML5-Canvas-to-FB-Twitter

    KOJO AMAKYE - October 22, 2016 reply

    Thanks I got it fixed. It was a problem with my FB app id all the while. Great post

  • Louis - October 27, 2016 reply

    Great tutorial! How would I modify the FB.api payload to allow the user to add a custom message before posting?

    Jerez Bain - October 27, 2016 reply

    Thanks! I’m glad it helped you out!
    The best way to approach customizing the share would be to give the user some UI other than the button to work with. Using the graph API, you can allow the user to share to a specific page, event, or group.
    For example, a modal would be great here with input fields to add additional information such as the a custom message or adjusting privacy settings.

    The additional information you collect can be used to assign values to the object in the FB.api request under ‘// Create facebook post using image’

    Reference: https://developers.facebook.com/docs/graph-api/reference/v2.8/user/feed -> ‘Publishing’ section

    Louis - October 28, 2016 reply

    Hi Jerez, thanks for the advice.

    Found a solution. Instead of the FB.api using FB.ui achieves this by creating the UI for the user:
    FB.ui({
    method: ‘feed’,
    display: ‘popup’,
    name: ‘Look at the awesome e-card created just for you!’,
    link: window.location.href,
    picture: response.images[0].source,
    privacy: ‘SELF’,
    },

    Jerez Bain - December 8, 2016 reply

    Cool, I’ll need to give this a try!

  • Jorge Loaiza - November 28, 2016 reply

    Thank you 😀

  • Jorge Loaiza - November 28, 2016 reply

    I have this error in twitter 🙁

    Uncaught TypeError: Cannot read property ‘oauth_token’ of undefined(…)

    DEMO: https://teravision-test.000webhostapp.com/

    Jerez Bain - December 8, 2016 reply

    Hi Jorge, I didn’t see the twitter login button in your demo. Were you able to figure it out?

  • Erik Baker - December 1, 2016 reply

    This has been a fantastic tutorial & I’m almost there.

    I’m absolutely stuck on the Twitter implementation. I get the popup window & twitter asks to authorize, but it doesn’t redirect me to the page like your example does (& no photo posts). Instead I get a Twitter page in the popup that gives me a pin number & tells me to go back to app to “complete the authorization process”.

    What do you set your OAUTH_CALLBACK to in the twitter.php/share-on-twitter.php (using your version from github) and what is set on the Twitter app itself? I’ve set it to “oob” per the Twitter docs, which gives the pin response described above. But if I set everything to my apps’ URL, it brings the app up inside the pop up & does not post the photo.

    Help, what am I doing wrong?

    Follow up question: Why doesn’t the Facebook Javascript SDK require the app secret like the PHP SDK version does? Is that secret exposed using your method?

    Jerez Bain - December 8, 2016 reply

    Hi Erik, if using the example directory on github, your OAUTH_CALLBACK should be set to your twitter-finish.php file in the auth folder: https://github.com/giovanniorigins/HTML5-Canvas-to-FB-Twitter/tree/master/auth
    For example: ‘www.example.com/auth/twitterfinish.php’

    Regarding Facebook, I think their API explains well why it isn’t required in the Javascript SDK – mainly because any client has access to your code so you don’t want people to have access to your app secret. Ref: https://developers.facebook.com/docs/facebook-login/security/#appsecret
    The secret isn’t exposed using my method because posting to Facebook is all handled within the client browser thanks to Oauth2. Unlike Twitter which is Oauth1 and needs an intermediate server to communicate with.

  • Janis Muiznieks - December 5, 2016 reply

    These “canvas.toDataUr” posts work great – big thanks for that code fragment. But stil I have problems with fact that it’s impossible to close that FB.login modal popup. Is there solution ? At the moment i read that i’m not the only one. Is there other ways to authorize FB not using that popup?

    Jerez Bain - December 8, 2016 reply

    Thanks Janis. Yes i agree the login modal can be annoying to figure out. The main reason it does not close is because there is usually an issue with the callback url or other Client OAuth Settings in your Facebook app settings. However, you could use the PHP SDK as a login flow instead of this.

  • DailyFoot - December 8, 2016 reply

    Hi thank for that tutorial. I m almost done, but i got an issue.
    here my log:
    Object {status: “connected”, authResponse: Object}
    jquery.min.js:4 POST https://graph.facebook.com/me/photos?access_token=EAAX4Q7eEK70BAPduWCm8Hmf…Goy8UBLuoz7TXqG3GbNfU9X5IJBdo20gJ8OaDmWqWMDqZA6coUd2OXTJtZCX7ZAs2ovWgZDZD 403 ()send @ jquery.min.js:4ajax @ jquery.min.js:4postImageToFacebook @ scripts.js:1101(anonymous function) @ scripts.js:1081v.__wrapper @ all.js:90ia @ all.js:87p @ all.js:114(anonymous function) @ all.js:92(anonymous function) @ all.js:90(anonymous function) @ scripts.js:1078dispatch @ jquery.min.js:3r.handle @ jquery.min.js:3
    scripts.js:1145
    error Status 403

    When i post the graph link i have that:

    {
    “data”: [

    ]
    }

    Jerez Bain - December 8, 2016 reply

    Hey, Thanks! I’m guessing this is when your are uploading the canvas image to facebook photos. What formData are you sending in this call?

    DailyFoot - December 9, 2016 reply

    Hi, Jerez
    I just used this: copied and past from this this tutorial.

    function postImageToFacebook(token, filename, mimeType, imageData, message) {
    var fd = new FormData();
    fd.append(“access_token”, token);
    fd.append(“source”, imageData);
    fd.append(“no_story”, true);

    // Upload image to facebook without story(post to feed)
    $.ajax({
    url: “https://graph.facebook.com/me/photos?access_token=” + token,
    type: “POST”,
    data: fd,
    processData: false,
    contentType: false,
    cache: false,
    success: function (data) {
    console.log(“success: “, data);

    // Get image source url
    FB.api(
    “/” + data.id + “?fields=images”,
    function (response) {
    if (response && !response.error) {
    //console.log(response.images[0].source);

    // Create facebook post using image
    FB.api(
    “/me/feed”,
    “POST”,
    {
    “message”: “”,
    “picture”: response.images[0].source,
    “link”: window.location.href,
    “name”: ‘Look at the cute panda!’,
    “description”: message,
    “privacy”: {
    value: ‘SELF’
    }
    },
    function (response) {
    if (response && !response.error) {
    /* handle the result */
    console.log(“Posted story to facebook”);
    console.log(response);
    }
    }
    );
    }
    }
    );
    },
    error: function (shr, status, data) {
    console.log(“error ” + data + ” Status ” + shr.status);
    },
    complete: function (data) {
    //console.log(‘Post to facebook Complete’);
    }
    });
    }

    Jerez Bain - December 9, 2016 reply

    Okay. So I see that you are getting a 403 error, correct? In your facebook app settings, did you request the ‘publish_actions’ permission when you made the app live?

    Also in the network tab of your browser’s developer tools you should be able to see the exact request that returned the 403 and also a possible explanation why.

    DailyFoot - December 9, 2016

    i didn t request for ‘publish_action’ i will do it right now.
    I tested this share button with my own account (admin account) and it doesn’t work.
    But i created a tester account and it work fine. I saw the shared post on the tester account wall.
    Thank you for your help!

    Jerez Bain - December 9, 2016

    Glad you got it working. Your admin account may have to grant your app publish_actions permissions for it to work since it had already asked for permissions before and might not ask again.

    DailyFoot - December 10, 2016

    I made my request to get “Publish_Action” facebook said i didn t need that because i use just a share button, so they don t give me the Auth.
    About my website peopple can create custom canvas image and can share it. (there own canvas)
    Is there a way to doing that without using API Graph ?

  • Ravneet KIS - February 1, 2017 reply

    Hi Jerez,

    Thanks for your tutorial.
    I’m using your tutorial to post image created in canvas to Facebook and Twitter. For Facebook, it works great but I’m facing problem in uploading base64 image to Twitter whereas posting text on Twitter works good.
    Every time I tries to upload image with text, it posts text without image with some errors:

    – Fatal error: Uncaught exception ‘AbrahamTwitterOAuthTwitterOAuthException’ with message ‘Operation timed out after 5000 milliseconds with 0 bytes received’ in C:wampwwwfancy2designervendorabrahamtwitteroauthsrcTwitterOAuth.php on line 400

    – AbrahamTwitterOAuthTwitterOAuthException: Operation timed out after 5000 milliseconds with 0 bytes received in C:wampwwwfancy2designervendorabrahamtwitteroauthsrcTwitterOAuth.php on line 400

    It will be appreciable if you can me to sort out this issue.
    Thanks

    Jerez Bain - February 1, 2017 reply

    Hey Revneet, have you checked that the canvas has been converted to a dataURL and that it is being sent along with the ajax request to ‘/auth/twitter.php’?

    Ravneet KIS - February 2, 2017 reply

    Hi Jerez, Thanks for the reply.

    Yes, canvas has been converted to a dataURL and it is being sent along with ajax request to /auth/share-on-twitter.php after getting authorization from /auth/twitter.php opened in a new window.
    I’m going to mention flow here:

    -> On click “Share Image on Twitter” button, /auth/twitter.php opens into a new window that asks for login to twitter to get authorized.
    -> After getting authorization, response with “oauth_token” and other details are send to page.
    -> After getting response, ajax request with form data (that includes status, image in base64 and “oauth_token” & “oauth_token_secret”) sends to /auth/share-on-twitter.php.
    -> On /auth/share-on-twitter.php, it establish connection with twitter and trying to upload image by calling the method $connection->upload(‘media/upload’, [‘media’ => $_REQUEST[‘image’]]);
    -> This method is located on /vendor/abraham/twitteroauth/src/TwitterOAuth.php.
    -> After reaching to upload method, it calls to new function called “uploadMediaNotChunked”.
    -> After this, private function “http” is called.
    -> Then, “oAuthRequest” function is called.
    -> After that, “request” function is called where I’m getting error at line 400:
    “throw new TwitterOAuthException(curl_error($curlHandle), curl_errno($curlHandle));”
    after sending request through CURL.

    Please let me know if you able find out the issue.
    Thanks

  • Seth Schoenfeld - February 21, 2017 reply

    Hi Jerez!

    I like you tutorial a lot. I’m trying it out myself and stuck though. I have the facebook app set up and the image sharing code from my app is all in place. I am successful at putting the image in my facebook profile without creating the story. It’s just when it’s time to create the story that it doesn’t work. Do I require publish_actions to just post to my own feed?

    Seth Schoenfeld - February 22, 2017 reply

    Update: I managed to get back the error message from the 2nd layer api call to post the image to the feed. The response.error message is “Service temporarily unavailable”

    Seth Schoenfeld - February 22, 2017 reply

    Update: It works now. Fb can’t scrape a page from localhost in time to generate the image share. As soon as I uploaded to a dev server, it worked fine. Thanks again for this great tutorial, Jerez!!

    Jerez Bain - February 22, 2017 reply

    Hi Seth, Glad you liked the tutorial! Sorry I didn’t reply sooner, but I’m glad you git it to work. Cheers!

  • Haris Ur Rehman - February 23, 2017 reply

    Hi, nice article. I have a question, can this upload procedure work from an intranet site ?

    Jerez Bain - February 23, 2017 reply

    Hi Haris, thank you. I believe it should be fine though, that depends on the outbound restrictions set for the intranet. I would suggest testing it first if that is possible for you.

    Haris Ur Rehman - February 23, 2017 reply

    Ok thanks

  • Seth Paine - March 27, 2017 reply

    Can I use this with HTML2Canvas?

    https://html2canvas.hertzen.com/

    Jerez Bain - March 27, 2017 reply

    Hi Seth,
    They should work well together, you just skip the first step of creating the canvas image because HTML2Canvas does it for you.

  • God Body - April 18, 2017 reply

    does this still work?

    Jerez Bain - April 18, 2017 reply

    Sure does

    Richie Pages - February 1, 2019 reply

    How about now? (Lot of comments saying it doesn’t)

  • Max - June 1, 2017 reply

    FYI there is a 90-day deprecation notice on the ‘picture’ field used in this tutorial to post images to a user’s Facebook feed: https://developers.facebook.com/docs/apps/changelog

    Max - June 1, 2017 reply

    The new method involves using the parameter “object_attachment” instead of “picture” and passing the image id instead of the URL, but there is an open bug when posting an image with a link: https://developers.facebook.com/bugs/1339531229457302/ :/

    Jerez Bain - June 1, 2017 reply

    Thanks for the info, Max! I had planned to update the tutorial soon to keep it relevant.

  • Ashley Gordon - June 22, 2017 reply

    The Facebook option no longer works. Can you update the code?

    Jerez Bain - June 22, 2017 reply

    Will do, thanks for letting me know.

    Jerez Bain - June 23, 2017 reply

    The code has been updated to v2.9

  • kkk - July 10, 2017 reply

    Hi, nice work! I tried the demo page and to click “post to facebook” but nothing happen. However, the twitter function is working. Wondering if the code for sharing to facebook is working fine?

    Jerez Bain - July 10, 2017 reply

    Hi, thanks! I just tested it and it successfully posted to my facebook wall. In the developer console is it giving any errors?

    kkk - July 10, 2017 reply

    I used the code in github, and got this error: Uncaught ReferenceError: blob is not defined. sdk.js
    Looks like FB sdk can’t define blob?
    I changed the version to 2.9 for fb.init in js.
    Not sure if I miss out something?
    Thank you.

    Jerez Bain - August 7, 2017 reply

    blob is being defined implicitly , just add something like:
    // Blob used for Facebook
    var blob;

    to the top of your js script/file, that should fix it

  • Louis Nel - July 31, 2017 reply

    I see the “picture” and “object_attachment” fields have been deprecated since 17 July for all API versions. Any way to use this method still?

  • Louis Nel - August 7, 2017 reply

    Hi There, for the Twitter callback to work, what should the parameter be in the Callback URL settings in Twitter? Thanks!

    Louis Nel - August 7, 2017 reply

    Think I found the solution via your reply to user Erik Baker below. The callback URL should be mydomain.com/auth/twitter-finish.php. Works like a charm! Thanks for the great example.

    Jerez Bain - August 7, 2017 reply

    Great that you got it to work!

  • Seth Schoenfeld - October 9, 2017 reply

    Not sure why, but when I make the image upload to my album, it works fine. When I go to post it, it posts some other scraped image. Doesn’t post the image uploaded. Not sure if this is because of updated fb policies, or ? ?

  • Venryx - December 5, 2017 reply

    For anyone wanting to upload multiple photos and then attach them to the same post, a solution can be found here: https://stackoverflow.com/a/47648063/2441655

  • Mehak Dhiman - January 30, 2018 reply

    Hey,

    I have to use this code for twitter post share. I got an error like window.twit is undefined after authenticate the user. Also, got the issue with popup window, actually popup window never closed automatically after authentication.

    Please suggest me how I resolve that issue.

  • shruti - March 12, 2018 reply

    Hi Jerez,

    thank you for nice tutorial but I am getting error like :ncaught TypeError: Cannot read property ‘oauth_token’ of undefined”. Kindly please help me…

    Jerez Bain - March 12, 2018 reply

    Hi Shruti, I’ll try me best!

    Is the issue happening after you try sharing to twitter?

  • Kahlil Ashanti - March 13, 2018 reply

    Hey Jerez great stuff man. Can you point me in the right direction to solve this error which occurs when I click the ‘#shareFb’ button: Uncaught DOMException: Failed to execute ‘toDataURL’ on ‘HTMLCanvasElement’: Tainted canvases may not be exported.

    Jerez Bain - March 13, 2018 reply

    Hey Khalil, thanks! If I remember correctly, that is a security issue. This may happen if your file path is in the address bar, like ‘file://’. In that case, if you setup a local development server, that would fix it. if that’s not an option, try adding this line after ‘var imageObj’ is declared: ‘imageObj.crossOrigin = “Anonymous”;’

    Kahlil Ashanti - March 14, 2018 reply

    Much appreciated Jerez, that produced the following: Access to image….from origin ‘null’ has been blocked by CORS policy: Invalid response. Origin ‘null’ is therefore not allowed access.

    Jerez Bain - March 17, 2018 reply

    I would suggest try setting up a dev environment on your computer or uploading it to a server to test

  • shruti - March 18, 2018 reply

    what I have add in OAUTH_CALLBACK ?? I m getting error like Uncaught TypeError: Cannot read property ‘oauth_token’ of undefined
    at Object.callback ((index):177) .Kindly advice me.

    Jerez Bain - March 18, 2018 reply

    Hi shruti,

    You must setup twitter authentication first, that will assign a value to ‘oauth_token’ when trying to share to twitter. please check the code on github for the example: https://github.com/jgiovanni/HTML5-Canvas-to-FB-Twitter/blob/master/auth/twitter.php

  • Emi - April 4, 2018 reply

    Hey Jerez! In your demo the facebook share is no longer working, and I get the same message error “Application Error: There was a problem getting data for the application you requested. The application may not be valid, or there may be a temporary glitch. Please try again later.” could you check it out? 🙁

    Jerez Bain - April 7, 2018 reply

    Hey Emi!

    I’ll test it out and let you know.

    Jerez Bain - April 13, 2018 reply

    Facebook required some changes possibly due to the whole privacy issue at the moment, so the app was set in development mode. Let me know if it is working now.

    Gator - April 26, 2018 reply

    Hey Jerez, I was trying to use the Facebook share demo as well but it doesn’t seem to work still. Do you have any suggestions?

    Jerez Bain - April 26, 2018

    Hey Gator, are you getting the same error that Emi got?

    Jerez Bain - April 26, 2018

    Hey Gator, I made some updates to the code, can you try it again?

    Gator - April 26, 2018

    Jerez,

    I get a modal popup now that says “connected, posting to Facebook” but it still gives a 403 error in the console.

    Jerez Bain - April 27, 2018

    ahhh i see now. When you were testing the app did you allow the requested permissions? The issue is that it does not have permission to upload the canvas image to your profile.

    Gator - April 27, 2018

    weird, it never asks for permissions. I’m using incognito and logging into my facebook, but once I log in, it never asks for permissions, just gets hung up on the “connected, posting to Facebook”

  • Alex Marek - May 22, 2018 reply

    Great tutorial, it worked until about a month ago, but now facebook removed publish_actions so there isn’t a way to share canvas image on fb anymore. Tried using share_open_graph but that doesn’t accept base64 encoded images.

  • Diego - June 27, 2018 reply

    From https://developers.facebook.com/blog/post/2018/04/24/new-facebook-platform-product-changes-policy-updates/

    “The publish_actions permission will be deprecated. This permission granted apps access to publish posts to Facebook as the logged in user. Apps created from today onwards will not have access to this permission. Apps created before today that have been previously approved to request publish_actions can continue to do so until August 1, 2018. No further apps will be approved to use publish_actions via app review. Developers currently utilizing publish_actions are encouraged to switch to Facebook’s Share dialogs for web, iOS and Android.”

  • Tommy - August 5, 2018 reply

    Hello !

    I’m very new in twitter aps so I don’t know what I must provide as callback URL. Is your “share-on-twitter.php” ? Because when I try it, I have php error because of authentification.

    Jerez Bain - August 11, 2018 reply

    Hey Tommy,

    When you create your twitter app at https://apps.twitter.com/ you need to set the callback URL to where the `twitter-finish.php` file is located on your server

    Tommy - September 7, 2018 reply

    Thank you very much !

  • Richie Pages - February 1, 2019 reply

    Facebook share on your demo receives error (plz fix as I would love to try this code out):

    “Facebook has detected GOrigins Labs isn’t using a secure connection to transfer information.
    Until GOrigins Labs updates its security settings, you won’t be able to use Facebook to log into it.”

Join the conversation