LoginSignup
6
2

More than 5 years have passed since last update.

Qiitaでも投げ銭がしたい!! ~chrome拡張入門~

Posted at

概要

少し前にtwitter上で仮想通貨(Monacoin)を投げ銭できるサービス「 tipmona 」を用いて、Qiitaの良記事に投げ銭できる拡張機能 DevelopMonaを作ったので、その過程を紹介します。

なお、今回作るのはコンテンツスクリプト(特定ページに要素が追加されるもの)です。
こんな感じになります。
無題.png

無題.png

manifest.json

jsonにはコメント構文がないらしいので、"(括弧で囲んだ部分:")"をコメントとします。
実際コピペするときは(括弧)の行を外してください。


{
    "manifest_version": 2 ,
    "name": "拡張機能の名前",
    "version": "0.1",
     "(バージョンを決める":")"
    "description": "拡張機能の説明",
    "icons": {
        "16": "{16pxアイコンのurl}"
    },
    "content_scripts": [
         {
              "matches": ["https://qiita.com/*"],
        "(今回は「Qiita上で投げ銭」がしたいので、Qiitaを指定します":")"

              "js": ["jquery-3.2.1.min.js", "main.js"],
        "(今回はJqueryを使いました":")"
         }
    ],
    "web_accessible_resources": [
        "*.png"
      ]
   "(これでページにPNGを使えるようになります":")"

}

main.js

作りたいものによってコードを書きます。

document.createElemtとかを使って要素をそのページに埋め込みます


var twitter;

slash = location.href.split("\/")
//URLをスラッシュで分ける ["https:","","qiita.com","著者","items","記事番号"]


if (slash[2] == "qiita.com" && slash.length == 6 && slash[4] == "items") {
  //Qiitaの記事ページかどうかを判定

    var author,
        twitte;
    jQuery(document).ready(function ($) {
        $('a.it-Header_authorName').each(function () {
            author = $(this).text().slice(1)
        })
    })
    //ページから一番下の著作者ボタンを探す


    setTimeout(function () {
        fetch('https://qiita.com/' + author).then(res => res.text()).then(txt => twitter = ($("li.newUserPageProfile_socialLink-twitter>a", txt).attr("href")));
    //そのページの著者のページへアクセスして、twitterへのリンクを取得

  }, 1000)//ページのロードを待つ


    setTimeout(function () {
        console.log(twitter.split("\/"))
        authorstwitter = twitter.split("\/")[3]
        //著者のTwitterIDを取得

        if (authorstwitter){ //twitter連携していれば
            const imageURL = chrome.extension.getURL('monage_button.png')
            const imageURL_on = chrome.extension.getURL('monage_button_on.png')


            const imageTag = `<a  href="https://twitter.com/intent/tweet?text=@tipmona tip @` + authorstwitter + ` 0.114 %23DevelopMona \n あなたの記事【` + document.title + `】に投げ銭です。詳しくはこちら \n https://monappy.jp/memo_logs/view/monappy/123">
<img src="${imageURL}" onmouseover="this.src='${imageURL_on}' "onmouseout="this.src='${imageURL}'" width="100px" height="28px" ></a>`
            const monage = $("div.it-AuthorInfo_footer > div").after(imageTag)
        }//twitter投稿へのリンク付きボタンを作る



    }, 3000)

}

デプロイ(?)

無題.png

Chromeでその他のツール→拡張機能 の後、
パッケージ化されていない拡張機能を読み込む フォルダを指定します。

終わりに

初めての開発のわりに、案外簡単にできたかなという印象です。
質問・意見などありましたらコメントください

6
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
6
2