Giter Site home page Giter Site logo

ellisonleao / sharer.js Goto Github PK

View Code? Open in Web Editor NEW
2.0K 52.0 196.0 803 KB

:on: :bookmark: Create your own social share buttons. No jquery.

Home Page: http://ellisonleao.github.io/sharer.js

License: MIT License

JavaScript 100.00%
javascript share-buttons social-network facebook twitter pinterest okru telegram whatsapp hackernews

sharer.js's Introduction


sharer.js

Follow me on twitter

Using Sharer.js on your project? Let me know!

Sharer.js is a very tiny JS library to create custom social share components on DOM elements for your website. No dependencies.

Documentation

Checkout the docs page for more info about installing and usage.

sharer.js's People

Contributors

adrienpoly avatar anirbandey303 avatar arthurmichel avatar dayuss avatar dependabot[bot] avatar eckosantoso avatar ellisonleao avatar ericalli avatar eyllanesc avatar frop avatar gotbahn avatar hacknug avatar holdoffhunger avatar imsky avatar jdaviderb avatar joshuadoshua avatar lleger avatar maestrojolly avatar maximilianoertel avatar nadchif avatar nickzuber avatar quizhpi avatar solsend2l avatar sparanoid avatar ssoulless avatar stanleynguyen avatar suadhuskic avatar tearoom6 avatar umrysh avatar xmalinov avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

sharer.js's Issues

Getting server ip over address when sharing on Facebook

Hey, i'm trying to share my content on Facebook with sharer.js + meteor with spiderable and when i hit the share btn, i just got Facebook trying to fetch data from my ip instead my domain and i never get the right image. Below my spiderable settings:

Template.frontArticleSingle.onCreated(function(){
  var self = this;
  self.autorun(function(){
    var slug = FlowRouter.getParam('slug');
    self.subscribe('artigoSingleHome', slug, {onReady: function() {
      var pagina = Artigos.findOne({ slug: slug });
      SEO.set({
        title: 'Sindicond - ' + pagina.titulo,
        description: pagina.conteudo,
        meta: {
          'property="og:title"': pagina.titulo,
          'property="og:site_name"': 'Sindicond',
          'property="og:description"': pagina.resumo,
          'property="og:image"': pagina.imagem,
          'property="og:image:type"': 'image/jpeg'
        }
      });
    }});
  });
});

How to add social counter?

Hello,
How to add social counter for social buttons. I have this code countUrl:"https://graph.facebook.com/?id={url}&access_token={accessToken}&callback={callback}",countCallback:function(t){return(t.share||{}).share_count||0}}
And I don't know how to insert it to sharer script and send it to html div.
Thank you.

Add multiple facebook sharing methods

There are multiple facebook sharing methods, according to doc. Also it seems that sharer.php method used in sharer.js lib is not presented in the doc.
There is a good article on multiple facebook sharing methods on scotch.io.

For example, it seems that the only way to share something with image dynamically generated on the client is to use Feed Dialog.

AMD support?

Hello!
Would like to use it with RequireJS as define module.

How to confirm social share was completed (question)

I wanted to use this lib to allow my app users to share some app content and in return I wanted to offer them discount code. So my question is how can I check for if the user successfully posted on the respective social platform so I issue a discount code.

OG META

Hi!
when version will be enabled OG META types

Button class

Instead of using button, i would like to use a div instead

<div class="sharer button" data-sharer="twitter" data-title="Checkout Sharer.js!" data-url="https://ellisonleao.github.io/sharer.js/">Share on Twitter</div>

This seems to work fine until I remove the .button class. Since this conflicts with bootstrap, I don't want to use this class name. Is it possible to user .sharer class on its own?

Ajax Problem

Hello it does not work with content that comes with ajax. Will you do a work for it ?

Manually initialize

How to manually init this so that it works inside dynamic content like Angular views?

Facebook closes Android Chrome while share dialog opens

I've been struggling for several days with facebook sharing dialog on android.

I know this is not directly related to this sharer library, but because you've got some experience & feedback with the thing, you may help me a lot.

The thing is, when I open a facebook share dialog on android chrome (with facebook try yourself or with sharer's link), the chrome closes automatically or, if it don't close, every buttons (friends, position, page selection & co) are not working.

This is happening on Android 6.0.x, Chrome 57.0.2987.132
This does not happens on Firefox (52.0.2).

This is happening with every Android phone I have tested.
Thanks a lot.

Doesn't work for WhatsApp :(

I am not sure, perhaps it isn't your code problem. But for me your WhatsApp API doesn't work.
However, others soc. net. share buttons works perfectly.

Random error in meteor.js

sometimes everything works fine
i reloaded several times the webpage and found that sharer dont always work

i see this error on browser terminal
Uncaught TypeError: Cannot read property 'index' of undefined (firefox)
Uncaught TypeError: Cannot read property 'index' of undefined (google chrome)
Uncaught SecurityError: Blocked a frame with origin "https://www.youtube.com" from accessing a frame with origin "http://localhost:3000". The frame requesting access has a protocol of "https", the frame being accessed has a protocol of "http". Protocols must match. (google chrome)

i see this errors and the sharer button doesnt work

Add support for facebook hashtags

Given Facebook supports passing a hashtag parameter to the url, I think it would be a good idea to add support for those on the library.

I can take a look at it if you'd like me to open a PR.

Consider using the data-sharer attribute as the selector instead of class .sharer

Changing L27 from var elems = document.querySelectorAll('.sharer'), to var elems = document.querySelectorAll('[data-sharer]'), relieves users from having to add a sharer class to any element they want to act as a share button.

data-sharer is a required attribute for all social sharing anyway, so it can be used to kill two birds with one stone here.

Bower package name

Hi,
Can you tell me why the name is sharerjs in the bower command line but the bower package name is sharer.js ?

This cause me an issue with a script I use to automatize bower package install / uninstall.
I made a special case for this package but I'd rather not...

Thanks

Update jsDelivr links

jsDelivr switched to a fully automated system, that can serve files from npm and GitHub. This means all future releases will be available automatically, but will use a new link structure.

I noticed that there are old links at http://www.ellison.rocks/sharer.js/, the correct link is https://cdn.jsdelivr.net/npm/sharer.js@latest/sharer.min.js.

You can find links for all files at https://www.jsdelivr.com/package/npm/sharer.js.

Feel free to ping me if you have any questions regarding this change.

Update npm package

Just a heads-up: Noticed that the version on npmjs.org is different. E.g. the pinterest button wouldn't show the image until I noticed that the media property isn't set in the npm version.

Doesn't position correctly in zoomed windows

When using on a zoomed out window or for example a window in Chromes responsive mode emulating a large screen, the popup doesn't open in the center. Depending on how much the screen is zoomed out or how much bigger the emulated screen is than the actual screen determines how far from the center the popup appears.

For example the actual width of the browser on my screen is 1440. When using the emulator to show the screen at 4330, the popup opens far off to the right on my other monitor.

I think the top and left properties of window.open are relative to the window outer dimensions and not the inner. The script uses inner width and height to make its calculation of where to put the popup, but this is not relative to the actual window width and height.

From some brief resarch (https://stackoverflow.com/questions/57652/how-do-i-get-javascript-to-open-a-popup-window-on-the-current-monitor) it doesn't sound like something super easy to solve.

Two popup window open

Hi. When I clicked the facebook or the other link buttons, two popup windows open. I have added this:
googleplus: {
shareUrl: 'https://plus.google.com/share?',
params: {
url: this.getValue('url'),
}
},

And the googleplus button works perfect. One window. But the other links(no whatsapp or telegram) open two same windows. What is wrong? Thanks.

/**
 * @preserve
 * Sharer.js
 *
 * @description Create your own social share buttons
 * @version 0.3.5
 * @author Ellison Leao <[email protected]>
 * @license GPLv3
 *
 */

(function (window, document) {
    'use strict';
    /**
     * @constructor
     */
    var Sharer = function(elem) {
        this.elem = elem;
    };

    /**
     *  @function init
     *  @description bind the events for multiple sharer elements
     *  @returns {Empty}
     */
    Sharer.init = function() {
        var elems = document.querySelectorAll('[data-sharer]'),
            i,
            l = elems.length;

        for (i = 0; i < l ; i++) {
            elems[i].addEventListener('click', Sharer.add);
        }
    };

    /**
     *  @function add
     *  @description bind the share event for a single dom element
     *  @returns {Empty}
     */
    Sharer.add = function(elem) {
        var target = elem.currentTarget || elem.srcElement;
        var sharer = new Sharer(target);
        sharer.share();
    };

    // instance methods
    Sharer.prototype = {
        constructor: Sharer,
        /**
         *  @function getValue
         *  @description Helper to get the attribute of a DOM element
         *  @param {String} attr DOM element attribute
         *  @returns {String|Empty} returns the attr value or empty string
         */
        getValue: function(attr) {
            var val = this.elem.getAttribute('data-' + attr);
            if (!val) return;
            // handing facebook hashtag attribute
            if (attr === 'hashtag') {
                if (!val.startsWith('#')) {
                    val = '#' + val;
                }
            }
            return val;
        },

        /**
         * @event share
         * @description Main share event. Will pop a window or redirect to a link
         * based on the data-sharer attribute.
         */
        share: function() {
            var sharer = this.getValue('sharer').toLowerCase(),
                sharers = {
                    facebook: {
                        shareUrl: 'https://www.facebook.com/sharer/sharer.php',
                        params: {
                            u: this.getValue('url'),
                            hashtag: this.getValue('hashtag'),
                        }
                    },
                    linkedin: {
                        shareUrl: 'https://www.linkedin.com/shareArticle',
                        params: {
                            url: this.getValue('url'),
                            mini: true
                        }
                    },
                    twitter: {
                        shareUrl: 'https://twitter.com/intent/tweet/',
                        params: {
                            text: this.getValue('title'),
                            url: this.getValue('url'),
                            hashtags: this.getValue('hashtags'),
                            via: this.getValue('via')
                        }
                    },
                    email: {
                        shareUrl: 'mailto:' + this.getValue('to'),
                        params: {
                            subject: this.getValue('subject'),
                            body: this.getValue('title') + '\n' + this.getValue('url')
                        },
                        isLink: true
                    },
                    whatsapp: {
                        shareUrl: 'whatsapp://send',
                        params: {
                            text: this.getValue('title') + ' ' + this.getValue('url')
                        },
                        isLink: true
                    },
                    telegram: {
                        shareUrl: 'tg://msg_url',
                        params: {
                            text: this.getValue('title') + ' ' + this.getValue('url')
                        },
                        isLink: true
                    },
                    viber: {
                        shareUrl: 'viber://forward',
                        params: {
                            text: this.getValue('title') + ' ' + this.getValue('url')
                        },
                        isLink: true
                    },
                    line: {
                        shareUrl: 'http://line.me/R/msg/text/?' + encodeURIComponent(this.getValue('title') + ' ' + this.getValue('url')),
                        isLink: true
                    },
                    pinterest: {
                        shareUrl: 'https://www.pinterest.com/pin/create/button/',
                        params: {
                            url: this.getValue('url'),
                            media: this.getValue('image'),
                            description: this.getValue('description')
                        }
                    },
                    tumblr: {
                        shareUrl: 'http://tumblr.com/widgets/share/tool',
                        params: {
                            canonicalUrl: this.getValue('url'),
                            content: this.getValue('url'),
                            posttype: 'link',
                            title: this.getValue('title'),
                            caption: this.getValue('caption'),
                            tags: this.getValue('tags')
                        }
                    },
                    hackernews: {
                        shareUrl: 'https://news.ycombinator.com/submitlink',
                        params: {
                            u: this.getValue('url'),
                            t: this.getValue('title')
                        }
                    },
                    reddit: {
                        shareUrl: 'https://www.reddit.com/submit',
                        params: {'url': this.getValue('url')}
                    },
                    vk: {
                        shareUrl: 'http://vk.com/share.php',
                        params: {
                            url: this.getValue('url'),
                            title: this.getValue('title'),
                            description: this.getValue('caption'),
                            image: this.getValue('image')
                        }
                    },
                    xing: {
                        shareUrl: 'https://www.xing.com/app/user',
                        params: {
                            'op': 'share',
                            'url': this.getValue('url'),
                            'title': this.getValue('title')
                        }
                    },
                    buffer: {
                        shareUrl: 'https://buffer.com/add',
                        params: {
                            url: this.getValue('url'),
                            title: this.getValue('title'),
                            via: this.getValue('via'),
                            picture: this.getValue('picture')
                        }
                    },
                    instapaper: {
                        shareUrl: 'http://www.instapaper.com/edit',
                        params: {
                            url: this.getValue('url'),
                            title: this.getValue('title'),
                            description: this.getValue('description')
                        }
                    },
                    pocket: {
                        shareUrl: 'https://getpocket.com/save',
                        params: {
                            url: this.getValue('url')
                        }
                    },
                    digg: {
                        shareUrl: 'http://www.digg.com/submit',
                        params: {
                            url: this.getValue('url')
                        }
                    },
                    stumbleupon: {
                        shareUrl: 'http://www.stumbleupon.com/submit',
                        params: {
                            url: this.getValue('url'),
                            title: this.getValue('title')
                        }
                    },
                    flipboard: {
                        shareUrl: 'https://share.flipboard.com/bookmarklet/popout',
                        params: {
                            v: 2,
                            title: this.getValue('title'),
                            url: this.getValue('url'),
                            t: Date.now()
                        }
                    },
                    weibo: {
                        shareUrl: 'http://service.weibo.com/share/share.php',
                        params: {
                            url: this.getValue('url'),
                            title: this.getValue('title'),
                            pic: this.getValue('image'),
                            appkey: this.getValue('appkey'),
                            ralateUid: this.getValue('ralateuid'),
                            language: 'zh_cn'
                        }
                    },
                    renren: {
                        shareUrl: 'http://share.renren.com/share/buttonshare',
                        params: {
                            link: this.getValue('url')
                        }
                    },
                    myspace: {
                        shareUrl: 'https://myspace.com/post',
                        params: {
                            u: this.getValue('url'),
                            t: this.getValue('title'),
                            c: this.getValue('description')
                        }
                    },
                    blogger: {
                        shareUrl: 'https://www.blogger.com/blog-this.g',
                        params: {
                            u: this.getValue('url'),
                            n: this.getValue('title'),
                            t: this.getValue('description')
                        }
                    },
                    baidu: {
                        shareUrl: 'http://cang.baidu.com/do/add',
                        params: {
                            it: this.getValue('title'),
                            iu: this.getValue('url')
                        }
                    },
                    douban: {
                        shareUrl: 'https://www.douban.com/share/service',
                        params: {
                            name: this.getValue('title'),
                            href: this.getValue('url'),
                            image: this.getValue('image')
                        }
                    },
                    okru: {
                        shareUrl: 'https://connect.ok.ru/dk',
                        params: {
                            'st.cmd': 'WidgetSharePreview',
                            'st.shareUrl': this.getValue('url'),
                            'title': this.getValue('title')
                        }
                    },
                    mailru: {
                        shareUrl: 'http://connect.mail.ru/share',
                        params: {
                            'share_url': this.getValue('url'),
                            'linkname': this.getValue('title'),
                            'linknote': this.getValue('description'),
                            'type': 'page'
                        }
                    }
                },
                s = sharers[sharer];

            // custom popups sizes
            if (s) {
                s.width = this.getValue('width');
                s.height = this.getValue('height');
            }
            return s !== undefined ? this.urlSharer(s) : false;
        },
        /**
         * @event urlSharer
         * @param {Object} sharer
         */
        urlSharer: function(sharer) {
            var p = sharer.params || {},
                keys = Object.keys(p),
                i,
                str = keys.length > 0 ? '?' : '';
            for (i = 0; i < keys.length; i++) {
                if (str !== '?') {
                    str += '&';
                }
                if (p[keys[i]]) {
                    str += keys[i] + '=' + encodeURIComponent(p[keys[i]]);
                }
            }
            sharer.shareUrl += str;

            if (!sharer.isLink) {
                var popWidth = sharer.width || 600,
                    popHeight = sharer.height || 480,
                    left = window.innerWidth / 2 - popWidth / 2 + window.screenX,
                    top = window.innerHeight / 2 - popHeight / 2 + window.screenY,
                    popParams = 'scrollbars=no, width=' + popWidth + ', height=' + popHeight + ', top=' + top + ', left=' + left,
                    newWindow = window.open(sharer.shareUrl, '', popParams);

                if (window.focus) {
                    newWindow.focus();
                }
            } else {
                window.location.href = sharer.shareUrl;
            }
        }
    };

    // adding sharer events on domcontentload
    if (document.readyState === 'complete' || document.readyState !== 'loading') {
        Sharer.init();
    } else {
        document.addEventListener('DOMContentLoaded', Sharer.init);
    }

    // turbolinks compatibility
    window.addEventListener('page:load', Sharer.init);

    // exporting sharer for external usage
    window.Sharer = Sharer;

})(window, document);

Add support for Whatapp web

Currently I can only get a whatsapp share dialog to open using a mobile device, with the app installed.

On a desktop, clicking the Whatsapp button does nothing. It'd be great if it would use Whatsapp web in this case:

i.e.

https://web.whatsapp.com/send?text=some text

Reinit sharer.js in Angular2 app

Hello,

I am dynamically adding some sharer.js links after page load, and need to reinit the sharer.js script once that new component is instantiated. I've tried Sharer.init(), window.Sharer.init(), document.Sharer.init()....all to no avail.

Has anybody else figured out how to reinit this script within angular2?

Sharer.js not compatible with Turbolinks

Im trying to use Sharer.js in my Rails app that uses Turbolinks, but it just doesn't work, I have to reload the page... any idea how you can make this plugin compatible with Turbolinks?

Making parameters optional

According to twitter doc, all of the parameters are optional, but when I try to share something without "via" parameter, there is a "via" section in the message box.

About the licensing

So you let other people help building your tool (open source) but sell it alone?

I'm asking myself where we would be if everybody would do that.

What if, for example, the jQuery team decides to do this?

Programatically trigger share window

Hello!

I find your plugin nice and thought to use it on a project.
What I'm trying to accomplish: when the user clicks on the button, I first want to do some checks (maybe an ajax) and only after everything is right I would like to fire the share window.
Is this possible somehow?

Regards!

Media Email and Facebook

Hello @ellisonleao , as your suggestion, i'll make a new issue here

first :
it's a suggestion for email, can we change data-to into data-from
because if someone ( call this one A ) want to share foo from a web to his friend ( call this one B )
A must remember B email, and input it in input box, so javascript or form can populate data-to
but it's more better if A input his email in data-form or that web can put something like [email protected] into data-from , after that thunderbird or outlook open, A only need to type B name, let the software generate his friend email, some email make itself hard to remember

second :
when i use facebook, it told me : Sorry, this feature isn't available right now: An error occurred while processing this request. Please try again later.

thanks for great project :)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.