User:Samwilson/LinkIndexToWikidata.js
Appearance
Note: After saving, changes may not occur immediately. Click here to learn how to bypass your browser's cache.
- Firefox / Safari: Hold Shift while clicking Reload, or press either Ctrl-F5 or Ctrl-R (Cmd-R on a Mac)
- Google Chrome: Press Ctrl-Shift-R (Cmd-Shift-R on a Mac)
- Internet Explorer: Hold Ctrl while clicking Refresh, or press Ctrl-F5
- Opera: Clear the cache in Tools → Preferences
For details and instructions about other browsers, see Wikipedia:Bypass your cache.
Code that you insert on this page could contain malicious content capable of compromising your account. If you are unsure whether code you are adding to this page is safe, you can ask at the central discussion page, Scriptorium. The code will be executed when previewing this page under some skins, including Monobook. You can in the interim if you wish to refresh the content sooner under another skin. |
Documentation for this user script can be added at User:Samwilson/LinkIndexToWikidata. |
( function ( mw, $ ) {
/** @var {string} The fully-qualified URL of the Index page. */
const indexPageUrl = 'https://en.wikisource.org/wiki/' + mw.config.get( 'wgRelevantPageName' );
/** @var {jQuery} The table cell to add info to. */
const $tableCell = $( '<td>' );
/**
* jQuery ajax result handler.
*/
function handleQueryResult( result ) {
if ( !result.results || !result.results.bindings || !result.results.bindings[0] || !result.results.bindings[0].item.value ) {
return;
var $out = $( '<span>' )
.addClass( 'error' )
.text( "This Index appears to not yet be referenced from a Wikidata item. Please go to the edition's item on Wikidata and add the following value for 'Wikisource index page' (P1957): " )
.append( $( '<code>' ).css( { fontSize: 'smaller', display: 'block' } ).text( indexPageUrl ) );
} else {
var itemUrl = result.results.bindings[0].item.value,
itemId = itemUrl.substring( "http://www.wikidata.org/entity/".length );
var $out = $( '<a>' )
.attr( 'href', itemUrl )
.attr( 'target', '_blank' )
.text( itemId );
}
$tableCell.prepend( $out );
}
/**
* Set up HTML, and send request to Wikidata Query Service.
*/
function queryWikidata() {
// First up, add a row to the metadata table, that we'll later add content to.
var $tableHeader = $( '<th>' )
.attr( 'class', 'ws-index-label' )
.text( 'Wikidata' );
$tableCell.attr( 'class', 'ws-index-value' );
var $row = $( '<tr>' )
.attr( 'class', 'ws-index-row' )
.append( $tableHeader, $tableCell );
$( '#ws-index-metadata tbody' ).prepend( $row );
// Now query for the Wikidata item.
const query = 'SELECT ?item WHERE { ?item wdt:P1957 <' + indexPageUrl + '> }'
url = 'https://query.wikidata.org/sparql?format=json&query=' + encodeURIComponent( query );
$.ajax( { url: url } ).done( handleQueryResult );
}
/**
* Entry point.
*/
function main() {
if ( mw.config.get( 'wgCanonicalNamespace' ) === 'Index' ) {
queryWikidata();
}
}
main();
}( mediaWiki, jQuery ) );