アプリ開発備忘録

PlayStationMobile、Android、UWPの開発備忘録

はてなブログにWeb Share APIを使用した共有ボタンを設置する

SNSが多様化する中、特定のサービスの対応を待つのは不毛です。Web Share APIを使用しましょう。なんで公式で無いんですかね。MastodonとかMisskeyとかはあるのに。

コード

<script type="text/javascript">
    (function () {
        window.addEventListener('load', () => {
            if (!window.navigator.share) {
                return
            }
            document.querySelectorAll(".social-buttons")
                .forEach((item) => {
                    item.innerHTML += `
<div class="social-button-item social-button-item-web">
    <a class="entry-share-button entry-share-button-web"
    title="共有する"
    rel="noopener noreferrer"
    ><svg xmlns="http://www.w3.org/2000/svg" height="24" viewBox="0 -960 960 960" width="24"><path d="M720-80q-50 0-85-35t-35-85q0-7 1-14.5t3-13.5L322-392q-17 15-38 23.5t-44 8.5q-50 0-85-35t-35-85q0-50 35-85t85-35q23 0 44 8.5t38 23.5l282-164q-2-6-3-13.5t-1-14.5q0-50 35-85t85-35q50 0 85 35t35 85q0 50-35 85t-85 35q-23 0-44-8.5T638-672L356-508q2 6 3 13.5t1 14.5q0 7-1 14.5t-3 13.5l282 164q17-15 38-23.5t44-8.5q50 0 85 35t35 85q0 50-35 85t-85 35Zm0-640q17 0 28.5-11.5T760-760q0-17-11.5-28.5T720-800q-17 0-28.5 11.5T680-760q0 17 11.5 28.5T720-720ZM240-440q17 0 28.5-11.5T280-480q0-17-11.5-28.5T240-520q-17 0-28.5 11.5T200-480q0 17 11.5 28.5T240-440Zm480 280q17 0 28.5-11.5T760-200q0-17-11.5-28.5T720-240q-17 0-28.5 11.5T680-200q0 17 11.5 28.5T720-160Zm0-600ZM240-480Zm480 280Z"/></svg></a>
</div>
                `
                });
            document.querySelectorAll(".social-button-item-web")
                .forEach((item) => {
                    item.addEventListener('click', async function () {
                        await webShare();
                    })
                });
        })
    })();

    async function webShare() {
        let title = document.querySelector(".entry-title a").innerText;
        let url = document.querySelector(".entry-title a").href
        await window.navigator.share({
            title: "記事を共有",
            text: title,
            url: url,
        });
    }
</script>

<style>
    .entry-share-button-web {
        background: lightskyblue;
        width: 24px;
        height: 24px;
        padding: 8px !important;
    }

    .social-button-item-web:hover {
        cursor: pointer;
    }
</style>

その他

アイコンには以下を使用。
https://fonts.google.com/icons