User:Atmark-chan/custom/wikidata-description-withLink.js

From Meta, a Wikimedia project coordination wiki

Note: After publishing, you may have to bypass your browser's cache to see the changes.

  • Firefox / Safari: Hold Shift while clicking Reload, or press either Ctrl-F5 or Ctrl-R (⌘-R on a Mac)
  • Google Chrome: Press Ctrl-Shift-R (⌘-Shift-R on a Mac)
  • Internet Explorer / Edge: Hold Ctrl while clicking Refresh, or press Ctrl-F5
  • Opera: Press Ctrl-F5.
/*
<< ja >>
標準名前空間のページで、ウィキデータ([[d:]])での説明を表示します。
表示されたテキストは、ウィキデータ項目へのリンクとなっています。

作者: Atmark-chan (https://ja.wikipedia.org/wiki/User:Atmark-chan)

以下の外装に対応しています:
* ベクター (Vector)
* ミネルバ・ノイエ (MinervaNeue)
* モダン (Modern)
* モノブック (Monobook)
* タイムレス (Timeless)

このスクリプトは、[[User:Rxy]]さんのスクリプト[[User:Rxy/wikidata-description.js]]を参考に一部改変し作成しました。
感謝申し上げます。

<< en >>
This shows the discription in wikidata ([[d:]]) of the page in article namespace.
The text will be a link to the wikidata content.

Author: Atmark-chan (https://ja.wikipedia.org/wiki/User:Atmark-chan)

This works right in the following skins:
* Vector
* MinervaNeue
* Modern
* Monobook
* Timeless
*/

mw.loader.using( 'mediawiki.ForeignApi', function() {
	/* Wikidata に紐づくIDを格納 */
	var WikidataQID = mw.config.get( 'wgWikibaseItemId' );
	/* Wikidata に紐づくID が null でなければ */
	if (WikidataQID !== null){
		/* Wikidata の API を叩いて説明を読みに行く関数を叩く */
		getWikidataDescription(WikidataQID);
	}

	function getWikidataDescription(WikidataQID){
		var api = new mw.ForeignApi( 'https://www.wikidata.org/w/api.php' );
		var lang = mw.config.get('wgContentLanguage');
		// https://www.wikidata.org/w/api.php?action=wbgetentities&ids=WikidataQID&props=descriptions&languages=(言語名)
		api.get(
			{
				action: 'wbgetentities',
				ids: WikidataQID,
				props: 'descriptions',
				languages: lang
			}
		).done(function(data){
			/* 説明の取得 */
			var description;
			if(typeof data.entities[WikidataQID].descriptions[lang] !== 'undefined'){
				description = data.entities[WikidataQID].descriptions[lang].value;
			} else {
				description = '(ウィキデータ項目を閲覧)';
			}
			/* 説明をつける場所を取得 */
			if (mw.config.get('skin') == 'minerva') {
				selector = '.minerva__tab-container';
			} else {
				selector = '#siteSub';
			}
			/* 説明を付ける */
			$(
				'<div id="wikidata-description-link">'
					+ '<a style="color:gray; font-size:90%;" href="//ja.wikipedia.org/wiki/d:' + WikidataQID + '">'
						+ description
					+ '</a>'
				+ '</div>'
			).insertBefore(selector);
		});
	}
});