User:Ch1902/wikientity.js

From Wikidata
Jump to navigation Jump to search

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.
/**
 * Tool to add [wiki] links beside the [edit] link of entities/statements on
 * a page to go to the selected language wiki without having to go to the entity
 * page first
 */
function statementWikiLinks (lang) {
   $('h1.wb-firstHeading .wb-editsection').append(
      $('.wb-sitelinks-link-' + lang + ' a').clone(false).text('wiki').before(' [ ').after(' ]')
   );
 
   $('.wb-statement-claim').each(function () {
      var stmt = $(this), snak = stmt.find('.valueview-value a').attr('href'), q = snak.substr(snak.lastIndexOf('/') + 1).toLowerCase(),
          tool = stmt.find('.wb-editsection'), key = lang.replace(/\-/g, '_') + 'wiki';
 
      tool.append(' [ ').append(
         $('<a/>').html(lang + 'wiki').on('click', function () {
            var link = this;
            if (link.getAttribute('href', 2) === '#') {
               $.ajax({
                  url: '//www.wikidata.org/w/api.php',
                  type: 'GET',
                  dataType: 'json',
                  data: {action: 'wbgetentities', ids: q, format: 'json', props: 'sitelinks'},
                  success: function (data) {
                     var links = data && data.entities && data.entities[q] && data.entities[q].sitelinks || {}, 
                         href = links[key] ? 'http://' + lang + '.wikipedia.org/wiki/' + links[key].title : '#error';
 
                     link.href = href;
                     window.open(href, '_blank');
                  }
               });
               return false;
            }
         }).attr('href', '#')
      ).append(' ]');
   });
}