LoginSignup
2
2

More than 3 years have passed since last update.

今見ているページのTwitter投稿を補助するブックマークレット【選択したテキスト+URL】

Last updated at Posted at 2020-07-01

ニュースやブログなど、何らかのサイトを見ていて
:bird:Twitterで投稿したいけど、シェアボタンが無くて不便!
ボタンはあるけど文章がついていないなどの経験はありませんか?
特に古い記事、ブログ以外のサイトなど。

そんな時にこのブックマークレットがあれば、ワンボタンで
タイトルまたはH1タグまたは【選択したテキスト】+
URL付きの投稿画面を表示出来ます。

sample.png

下記のコードをコピペして、ブラウザのブックマークの
URLに貼り付ける事で利用できます。
※PC版Chromeで動作確認しています。2020.07.01現在

選択しているテキストを文章とする版

javascript:tt=window.getSelection().toString();window.open('https://twitter.com/intent/tweet?url='+encodeURI(location.href)+'&text='+encodeURI(tt),'_blank')

ページタイトル版

javascript:tt=document.title;window.open('https://twitter.com/intent/tweet?url='+encodeURI(location.href)+'&text='+encodeURI(tt),'_blank')

H1があればH1のテキストを、なければページタイトルを使う版

javascript:tt="";if(document.getElementsByTagName('h1')[0]==undefined){tt=document.title;}else{tt=document.getElementsByTagName('h1')[0].textContent;}window.open('https://twitter.com/intent/tweet?url='+encodeURI(location.href)+'&text='+encodeURI(tt),'_blank')

コード解説(H1版)

すごく単純なものです。h1タグが存在するかを確認し、
存在無ければタイトルを、存在すればh1内のテキストを使います。
tt="";if(document.getElementsByTagName('h1')[0]==undefined){tt=document.title;}else{tt=document.getElementsByTagName('h1')[0].textContent;}

location.hrefでURLを取得します。
日本語に対応するためURLもテキストもエンコードします。
window.open('https://twitter.com/intent/tweet?url='+encodeURI(location.href)+'&text='+encodeURI(tt),'_blank')

利用イメージと利用方法

1.適当なブックマークを作ります。名前も適度に付けます。
2.そのURLを上記のコードにします。Javascript:~を貼り付ける
3.投稿したいサイトを開いている時にこのブックマークを押す

画像はGoogleが対象サイトだった場合の例です。

tw.gif

※画像追加しました。

例、説明ページも下記に用意しました
http://allcountry.sakura.ne.jp/biz/code/javascript/20201001/texttwitter.html

2
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
2
2