Share facebook twitter javascript

Элементарные социальные share-кнопки

В ответ на посты о кнопках для шаринга в социальных сетях с громоздким исходным кодом, и сложной детальной кастомизацией, хочу показать хабрасообществу решение которое однажды написал неизвестный, но однозначно добрый программист. Автор сего чуда не я, но использую это решение уже больше года в проектах с которыми работаю.

HTML

Share = < vkontakte: function(purl, ptitle, pimg, text) < url = 'http://vkontakte.ru/share.php?'; url += 'url=' + encodeURIComponent(purl); url += '&title=' + encodeURIComponent(ptitle); url += '&description=' + encodeURIComponent(text); url += '&image=' + encodeURIComponent(pimg); url += '&noparse=true'; Share.popup(url); >, odnoklassniki: function(purl, text) < url = 'http://www.odnoklassniki.ru/dk?st.cmd=addShare&st.s=1'; url += '&st.comments=' + encodeURIComponent(text); url += '&st._surl=' + encodeURIComponent(purl); Share.popup(url); >, facebook: function(purl, ptitle, pimg, text) < url = 'http://www.facebook.com/sharer.php?s=100'; url += '&p[title]=' + encodeURIComponent(ptitle); url += '&p[summary]=' + encodeURIComponent(text); url += '&p[url]=' + encodeURIComponent(purl); url += '&p[images][0]=' + encodeURIComponent(pimg); Share.popup(url); >, twitter: function(purl, ptitle) < url = 'http://twitter.com/share?'; url += 'text=' + encodeURIComponent(ptitle); url += '&url=' + encodeURIComponent(purl); url += '&counturl=' + encodeURIComponent(purl); Share.popup(url); >, mailru: function(purl, ptitle, pimg, text) < url = 'http://connect.mail.ru/share?'; url += 'url=' + encodeURIComponent(purl); url += '&title=' + encodeURIComponent(ptitle); url += '&description=' + encodeURIComponent(text); url += '&imageurl=' + encodeURIComponent(pimg); Share.popup(url) >, popup: function(url) < window.open(url,'','toolbar=0,status=0,width=626,height=436'); >>; 
Счетчик шаринга

В случаях, когда надо вести подсчет количества шаринга страницы для каждой из социальных сетей любым возможным способом, а не конкретной кнопкой, здесь конечно идеальный вариант.

Читайте также:  String in javascript concatenation

Но у меня стояла другая задача, надо было отследить статистику нажатий именно на кнопку шаринга размещенную непосредственно на расшариваемой странице. Далеко не уходя от способа шаринга представленного выше, эта задача была решена табличкой в БД, еще одним параметром функции и простым ajax’ом:

 popup: function(url,soc) < window.open(url,'','toolbar=0,status=0,width=626,height=436'); $.post('/social/share', , function (data)<>); > 

В моем случае принимающий скрипт достает с URL айдишник записи, заносит в табличку запись и/или увеличивает счетчик на 1 для конкретной социальной сети.

Данное решение является самым минималистичным из мною встречаемых, с свободной кастомизацией внешнего вида. Оно избавляет от надобности в использовании сторонних сервисов типа pluso.ru и дает возможность вести собственную статистику на своем же сервере.

Источник

Saved searches

Use saved searches to filter your results more quickly

You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window. Reload to refresh your session.

Social media share. This project is intended to help you integrate sharing within your code. Supports Facebook, Reddit, Twittier, Telegram, Whatsapp, VK, OK.ru and many others.

License

delfimov/JS-Share

This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Name already in use

A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?

Sign In Required

Please sign in to use Codespaces.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching Xcode

If nothing happens, download Xcode and try again.

Launching Visual Studio Code

Your codespace will open once ready.

There was a problem preparing your codespace, please try again.

Latest commit

Git stats

Files

Failed to load latest commit information.

README.md

JS-Share — social and messengers sharing

Easy to use social media share library. This project is intended to help you integrate sharing within your code.

  • Small size
  • Vanilla javascript
  • No dependency
  • IE9+, Chrome, Safari, Firefox support
  • CSS styling is up to you
  • Supports AMD/CommonJS

JavaScript Share supports npm under the name js-share .

Download the script here and include it (unless you are packaging scripts somehow else):

script src pl-s">/path/to/jsshare.js">script>

Do not include the script directly from GitHub (http://raw.github.com/. ). The file is being served as text/plain and as such being blocked in Internet Explorer on Windows 7 for instance (because of the wrong MIME type). Bottom line: GitHub is not a CDN.

JavaScript Share can also be loaded as an AMD or CommonJS module.

Supported sharing platforms

  • Facebook
  • Twitter
  • LinkedIn
  • VK
  • OKru
  • Google+
  • GoogleBookmarks
  • Reddit
  • Tumblr
  • Pinterest
  • Weibo
  • Baidu
  • Mail.Ru
  • Line.me
  • Telegram
  • WhatsApp
  • Viber
  • Skype
  • Email
div>Share: button class pl-s">btn btn-default social_share" data-type pl-s">fb">Facebookbutton> button class pl-s">btn btn-default social_share" data-type pl-s">twitter">Twitterbutton> button class pl-s">btn btn-default social_share" data-type pl-s">vk">VK.combutton> button class pl-s">btn btn-default social_share" data-type pl-s">ok">OK.rubutton> button class pl-s">btn btn-default social_share" data-type pl-s">mailru">Mail.Rubutton> button class pl-s">btn btn-default social_share" data-type pl-s">gplus">Google+button> button class pl-s">btn btn-default social_share" data-type pl-s">googlebookmarks">Google Bookmarksbutton> button class pl-s">btn btn-default social_share" data-type pl-s">livejournal">LiveJournalbutton> button class pl-s">btn btn-default social_share" data-type pl-s">tumblr">Tumblrbutton> button class pl-s">btn btn-default social_share" data-type pl-s">pinterest">Pinterestbutton> button class pl-s">btn btn-default social_share" data-type pl-s">linkedin">LinkedInbutton> button class pl-s">btn btn-default social_share" data-type pl-s">reddit">Redditbutton> button class pl-s">btn btn-default social_share" data-type pl-s">mailru">Mail.rubutton> button class pl-s">btn btn-default social_share" data-type pl-s">weibo">Weibobutton> button class pl-s">btn btn-default social_share" data-type pl-s">line">Line.mebutton> button class pl-s">btn btn-default social_share" data-type pl-s">skype">Skypebutton> button class pl-s">btn btn-default social_share" data-type pl-s">telegram">Telegrambutton> button class pl-s">btn btn-default social_share" data-type pl-s">whatsapp">Whatsappbutton> button class pl-s">btn btn-default social_share" data-type pl-s">viber">Viberbutton> button class pl-s">btn btn-default social_share" data-type pl-s">email">Emailbutton> div>
import JSShare from "js-share"; var shareItems = document.querySelectorAll('.social_share'); for (var i = 0; i  shareItems.length; i += 1)  shareItems[i].addEventListener('click', function share(e)  return JSShare.go(this); >); >
import JSShare from "js-share"; var shareItems = document.querySelectorAll('.social_share'); JSShare.options.url = "http://www.example.com/fancy/url"; for (var i = 0; i  shareItems.length; i += 1)  shareItems[i].addEventListener('click', function share(e)  return JSShare.go(this); >); >

See working demo example.html .

  • data-type — where to share. Required.
  • data-url — URL to share. Default value is the current page location ( location.href ).
  • data-title — title to share. Default is the current page title ( document.title ).
  • data-text — share description. Only for vk, ok, googlebookmarks, lj, tumblr, linkedin, mailru, email.
  • data-utm_source — utm_source for links. Default is none.
  • data-utm_medium — utm_medium for links. Default is none.
  • data-utm_campaign — utm_campaign for links. Default is none.
  • data-popup_width — popup width. Default is 626 pixels.
  • data-popup_height — popup height. Default is 436 pixels.

Same options could be used on script initialization.

data-title and data-text are optional and will be ignored by some services. Social networks usually get all required data from Open Graph metadata ( og:* tags).

button class pl-s">social_share" utm_source pl-s">messengers" data-utm_medium pl-s">telegram" data-type pl-s">telegram">Telegrambutton> button class pl-s">social_share" utm_source pl-s">messengers" data-utm_medium pl-s">whatsapp" data-type pl-s">whatsapp">Whatsappbutton> button class pl-s">social_share" utm_source pl-s">messengers" data-utm_medium pl-s">viber" data-type pl-s">viber">Viberbutton>
button class pl-s">social_share" utm_source pl-s">messengers" data-utm_medium pl-s">vk" data-url pl-s">http://www.example.com/fancy/url" data-type pl-s">vk">VK.combutton> button class pl-s">social_share" utm_source pl-s">messengers" data-utm_medium pl-s">fb" data-url pl-s">http://www.example.com/fancy/url" data-type pl-s">fb">Facebookbutton> button class pl-s">social_share" utm_source pl-s">messengers" data-utm_medium pl-s">ok" data-url pl-s">http://www.example.com/fancy/url" data-type pl-s">ok">OK.rubutton>

About

Social media share. This project is intended to help you integrate sharing within your code. Supports Facebook, Reddit, Twittier, Telegram, Whatsapp, VK, OK.ru and many others.

Источник

Sharer.js

Sharer.js is a lightweight js lib to create custom social share components on DOM elements for your website. No dependencies.

Installing:

Using NPM

Grabbing the latest min version and adding to your page

Adding share behaviour to a component

Sharer.js currently supports more than 20 social media sites:

Each sharer component has its own

All sharer objects can accept the following attributes:

  • data-title — sharer text
  • data-url — url to be shared
  • data-width — popup width
  • data-height — popup height
  • data-link — share element will work as a link
  • data-blank (requires data-link combined) — share element will work as a link in a new tab

Manual event binding

Manual event binding is now supported from versions 0.3.1 and above through the window.Sharer object.

You can now dynamically bind share events using the sharer.js library. Example using jQuery:

Share components

Twitter:

Available custom attributes:

  • data-via (optional: twitter username without @)
  • data-hashtags (optional: comma separated hashtags)

Facebook:

Available custom attributes:

Linkedin:

Email

Available custom attributes:

WhatsApp

Available custom attributes:

  • data-to (Phone number 9999999999 format)
  • data-web (send to whatsapp web instead of desktop/mobile version)
  • data-description (optional)

Share on Whatsapp Web
Share on Whatsapp

Telegram

Viber

Pinterest

Available custom attributes:

Tumblr

Available custom attributes:

Hackernews

Available custom attributes:

Reddit

VK

Available custom attributes:

Buffer

Available custom attributes:

Xing

Источник

Оцените статью