Giter Club home page Giter Club logo

koddr / goodshare.js Goto Github PK

View Code? Open in Web Editor NEW
487.0 15.0 46.0 32.67 MB

🚀 А useful modern JavaScript solution for share a link from your website to social networks or mobile messengers. Easy to install and configuring on any of your website!

Home Page: https://goodshare.js.org

License: MIT License

JavaScript 99.57% Makefile 0.43%
social-network share-counters javascript counter share without-jquery jsdelivr js share-buttons hacktoberfest

goodshare.js's Introduction

🚀 goodshare.js

Share a link from your website to social networks and mobile messengers

goodshare.js logo github

npm version bundle size jsDelivr download code style: prettier license twit link

A useful modern JavaScript solution for share a link from your website to social networks or mobile messengers.
Easy to install and configuring on any of your website!

The Why?

Simple install, extensive documentation, developer support, SEO friendly, small bundle size 1.04 KB (with all dependencies, minified and gzipped), many options for customization of appearance, clean code without scripts tracking user activity on the page, high speed.

Installation

Install via npm or pnpm or yarn :

npm install goodshare.js
pnpm add goodshare.js
yarn add goodshare.js

Or include from jsDelivr CDN:

<script src="https://cdn.jsdelivr.net/npm/goodshare.js@6/goodshare.min.js"></script>

Usage

Works with any HTML tags: <a>, <div>, <button> or other. Choose any and add required attributes data-social.

Full list of supported social providers and mobile messengers.

<!-- Create button with share to Twitter -->
<button data-social="twitter">Share this to Twitter</button>

<!-- Create link with share to Facebook -->
<a href="#" data-social="facebook">Share this to Facebook</a>

<!-- Create div container with share to LinkedIn -->
<div data-social="linkedin">Share this to LinkedIn</div>

<!-- Create icon from Fontello.com with share to Tumblr -->
<i class="icon-tumblr" data-social="tumblr"></i>

By default, goodshare.js search this tags for get title, description and image (for some social networks):

<head>
  <title>Current page title</title>
  <meta name="description" content="Current page description.">
  <link rel="apple-touch-icon" href="http://example.com/path/to/image.png">
  ...
</head>

Framework components

Size limit report

npm run size

  Time limit:   80 ms
  Size:         1.06 kB gzipped
  Loading time: 21 ms   on slow 3G
  Running time: 54 ms   on Snapdragon 410
  Total time:   75 ms

Thanks to Andrey Sitnik @ai/size-limit.

Developers

Project assistance

If you want to say «thank you» or/and support active development goodshare.js:

  1. Add a GitHub Star to project.
  2. Twit about project on your Twitter.
  3. Join DigitalOcean at our referral link (your profit is $100 and we get $25).

Thanks for your support! 😘 Together, we make this project better every day.

DigitalOcean Referral Badge

Stargazers over time

Stargazers over time

Code Contributors

This project exists thanks to all the people who contribute.

License

MIT

goodshare.js's People

Contributors

amirhmoradi avatar dependabot-preview[bot] avatar dependabot[bot] avatar devxom avatar kanfet avatar kitae0831 avatar koddr avatar lukasdrgon avatar moimikey avatar monkeywithacupcake avatar mschilder avatar x35a 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

goodshare.js's Issues

Google+ не отображается счетчик

На данный момент стоит в счетчике 0.

Сделал замену на JSON от share.yandex.ru.

Код:

            /*
             *  Share counter > Google Plus
             *  @see https://developers.google.com/+/
             */
            if (existCount('[data-counter="gp"]')) {
                $.getJSON('https://share.yandex.ru/gpp.xml?url=' + encodeURIComponent(location.href) + '&callback=?', function(response) {
                    if (response.share === undefined) $('[data-counter="gp"]').text('0');
                    else $('[data-counter="gp"]').text(roundCount(response.share.share_count));
                });
            };

Simple email sharing

Hi,

goodshare.js is great, however, I miss the simple email share button, there is one for Russia, but not the general email share button.

Is it possible to add it ?

Thanks in advance,

Google Plus doesn't work

Google Plus with counter doesn't work. It doesn't show counter number and gplus pop-up shows the following error message:
"That link isn't valid. Check it and try again."

Получение количества расшаренных

Добрый день. А можно получить общее количество всех расшаренных (например фотографий) в одном месте? Ну т.е. все фотографии в фейсбук расшарили 25 раз?

The parameters do not work for facebook?

Hi!
I'm using button with this mark-up:

<button class="goodshare"
        data-type="fb"
        data-url="http://hohlov.pro/goodshare/page2.html"
        data-title="Second page (data)"
        data-text="Second page description(data)"
        data-image="http://hohlov.pro/goodshare/og2.png">
    fb
</button>

For VK it work's fine.
But for Facebook - don't work.

If page in data-url exist - it's get params from that page. If don't exist - get params from 404 error.

Live example: http://hohlov.pro/goodshare/

Don`t wokr data parametrs

Hi.
For the share link I want to put a picture and a title. Here is my link: <a href="#" data-title="test title" data-social="facebook" data-image="/telecom/img/share3.png"> <i class = "fa fa-facebook" > </ i> </a>
As a result I have this https://snag.gy/u0Ni34.jpg
Where was I wrong?

Значение по умолчанию

Здравствуйте. Спасибо за Ваш труд! Хотелось бы иметь возможность задавать значение по умолчанию counter.share 0 или пустое значение. Для себя руками поправил, но, думаю, эта возможность будет полезна общественности.

Реч идет о таких строках:

counter.share > 0 ? counter.share.share_count : 0;

Заменил на

counter.share > 0 ? counter.share.share_count : '';

Facebook, Googleplus and Stumbleupon Cannot Share The Correct Data

Overview of the problem

Hi Guys,

  1. It seems like the facebook and googleplus cannot get the correct URL or anything else, The old version can get the image and the post title and description but now it can get the main URL only like [https://domain.com]

  2. Stumbleupon convert into mix.com and it no longer available so the share URLs generates

<a class="goodshare" href="#" 
data-social="facebook" 
data-url="https://oxibug.com/example/2018/08/07/cannot-use-facebook-and-googleplus-share/" 
data-title="Cannot use Facebook and Googleplus Share Buttons" 
data-description="It seems like theres a problem" 
data-image="https://oxibug.com/example/wp-content/uploads/2018/07/35.jpg">

    <i class="socicon socicon-facebook"></i>

</a>

<a class="goodshare" href="#" 
data-social="googleplus" 
data-url="https://oxibug.com/example/2018/08/07/cannot-use-facebook-and-googleplus-share/" 
data-title="Cannot use Facebook and Googleplus Share Buttons" 
data-description="It seems like theres a problem" 
data-image="https://oxibug.com/example/wp-content/uploads/2018/07/35.jpg">

    <i class="socicon socicon-googleplus"></i>

</a>

Screenshots

  1. Facebook Issue

  2. Stumbleupon Issue

Steps to Reproduce

Configuration

  • Browser: Chrome 68
  • OS/Device: Windows 8.1
  • goodshare.js: 5.1.1

Facebook sharing doesn't seem to work

I tried Facebook, Twitter and LinkedIn sharing and while Twitter and LinkedIn seem to work, Facebook gives an error in the sharing dialog. Error says something like: "This functionality is not available now. Error while processing the request. Try again later."

Array.from() ошибка в ie

Здравствуйте! Обнаружилась ошибка в ie11, связана с отсутствием поддержки метода Array.from()
версия "goodshare.js": "^4.0.6"
http://joxi.ru/krD7od1IEWjMBA
http://joxi.ru/52aJDoNu4Bz9PA

Могли бы вы добавить полифилл для метода? Вот рабочий полифилл https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/from?v=control#Polyfill
Заранее спасибо!

Смена ссылки Telegram

Здравствуйте, подскажите как можно изменять ссылку для Telegram, сделать вот так
t.me/iv?url=...&rhash=...
когда например указаны дополнительные параметры в data-*
это нужно для работы с Instant View Telegram

Reddit

Каждый раз выполняется XHR запрос к Reddit API.

Обработка события получения всех счетчиков.

Нет ли возможности (или в планах) добавить возможность привязать свою функцию на событие поучение всех ответов? (Или просто при получении отдельного ответа с признаком соцсети)?

Refreshing when new links added to page dynamically

How would I go about refreshing Goodshare to re-scan the page for social links?

Use case is when new articles are loaded into the page via AJAX. Currently as the links are injected into the page after Goodshare is included, the links have correct data-social attributes but do not have Goodshare events attached.

Доработки скрипта.

Здравствуйте. Я для своих нужд доработал ваш скрипт. Сделал возможность использования нескольких блоков шары с различными урл на одной странице, получение информации об урл, заголовке, описании, изображении для шары из data-аттрибутов ссылки. Хотелось бы видеть это у вас. Могу поделать пулл-реквесты, если это нужно. Измененный файл прилагаю.
goodshare.js.zip

Counters don't work

К сожалению, счётчики к кнопкам не работают. Вне зависимости от количества лайков фейсбук и G+ всегда ноль. Одноклассники и ВК всегда единица. Это даже видно в файле index.html, который идёт в архиве со скриптом

Set minimum shares for share count

The share count is a great feature too increase shares, but if an article has 0 shares it can have an opposite effect.

Is there a way to display share counts only when there is at least 1 share? (Or maybe let the user define a minimum number of shares before showing the share count).

Thanks for this great plugin, it´s easily the best social sharing plugin I´ve found!

Bad Request при запросе "поделиться" в ВК на отдельных страницах

При нажатии на кнопку "Поделиться в ВК" открывается пустое окно с заголовком "400 Bad Request" (http://vk.com/err400.html). Но не везде, а примерно на половине страниц.
Пример "сбойной" страницы: http://kurantynew.ru/new/2016/04/15/a-mne-letat-ohota/
и "нормальной": http://kurantynew.ru/new/2016/03/25/dialog-o-poligone/

Facebook doesn't work

Facebook with counter doesn't work. It shows counter number 0 however you can't share anything and get this error message:
"Sorry, this feature isn't available right now: An error occurred while processing this request. Please try again later."

Двузначный код

В атрибутах data-type и data-counter нужно указывать двузначный код из таблицы «Список поддерживаемых социальных сетей и микроблогов».
При использовании двузначного кода эта либа не работает. Работает только при использовании data-type="facebook" ...

VK счетчик

Неверно работает счетчик ВК. Пример ответа API: VK.Share.count(1, 95); Вы берете первое значение, а нужно второе. Так же было бы неплохо суммировать показатели http и https.

Total count?

Hello! Can you help me, get total count social activities?

Добавьте секцию main

Здравствуйте, добавьте секцию main в bower.json, это нужно для сборщиков проекта.

Вопрос по fb и ok

При шаринге fb и ok, в url попапа не передаются data-text и data-image.
Речь об этом участке http://joxi.ru/krD7od1IEM0qQA
Вопрос поддерживают ли fb и ok передачу описания, и картики в url попапа? Например для vk в url передаются все data- параметры.

Более корректный шаринг в Телеграм с выбором собеседника

Сделал замену шаринга в телеграм, при котором можно выбрать собеседника, или группу, куша расшаривать. В текущем варианте открывается только приложение (на десктопе смотрел) и более ничего.

Код:

return 'https://telegram.me/share/url?url=' + encodeURIComponent(options.url);

Add docs on how to dynamically change the attributes

Maybe you can add a small section in readme on how to change the attributes manually with jQuery. Reason is that $.attr('data-url', 'value') will only work on the first call due to internal jQuery cache. So one should use $.data('url', 'value') instead.

Might save people some time when the docs explicitly make use of $.data().

.data()
The data- attributes are pulled in the first time the data property is accessed and then are no longer accessed or mutated (all data values are then stored internally in jQuery).

Change default text source

Hi,
Goodshare uses description meta tag's content as a text for share. I couldn't find any way to change it. I don't want to use my description to share in twitter.
Is there any way to change text source?

counter for custom url

Здравствуйте,
а можно без пересборки задавать url, например через data-url для подсчета лайков? и почему-то не работает VK когда вписываешь url внутри js файла (с фейсбуком все нормально)

в моей задаче интересно было бы использовать ваше решение но со страницей, где например голосовалка в виде лайков поэтому чей заданый url победит тот и выиграет.

No 'decortion options'

Hi
You say "This example shows one of decoration options with all supported social networks" and follow it with a beautiful picture showing buttons and icons.
However, there is no documentation on this feature anywhere and I can see nothing in the code that would generate it. How do you activate this 'option' please?

Thank you.

Frankie

Configurator is missing

The configurator mentioned in readme is nowhere to be found on your website. Every link leading to it is not functional. Is it still work in progress?

Событие получения данных

Здорово было бы иметь возможность повесить обработчик на получение данных от всех сервисов.

При этом, иметь доступ, в этот момент, ко всем неокругленным цифрам

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.