User:Sanqui/referenceurl.js

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)
  • Edge: Hold Ctrl while clicking Refresh, or press Ctrl-F5.
/*

 Note to self: Use these tools to debug issues when developing MediaWiki userscripts:
 https://meta.wikimedia.org/wiki/User:Jon_(WMF)/Edit_to_user_or_gadget_script#How_can_I_avoid_triggering_errors?

*/

$(function($){
    const listview = document.querySelector('.wikibase-listview');

    const observer = new MutationObserver(() => {
      const statementviews = listview.querySelectorAll('.wikibase-statementview');

      statementviews.forEach(statementview => {
        const references = statementview.querySelector('.wikibase-statementview-references .wikibase-addtoolbar');
        
        if (!references) return;
        if (references.querySelector(".custom-add-url")) return;
        
        const newElement = document.createElement('span');
        newElement.innerHTML = '<a class="custom-add-url" style="position:relative;top:-5px;"><span class="wb-icon">🔗</span></a>';
        references.appendChild(newElement);
        
        newElement.addEventListener('click', () => {
          const referencesContainer = statementview.querySelector('.wikibase-statementview-references');
          const listViewObserver = new MutationObserver(() => {
            const listView = referencesContainer.querySelector('.wikibase-listview:last-child');
            if (!listView) return;
            const propertyInput = listView.querySelector('.wikibase-snakview-property input');
            if (!propertyInput) return;
            const text = 'P854';

            propertyInput.focus(); // Ensure the input field has focus
            propertyInput.value = text;
            propertyInput.dispatchEvent(new InputEvent('input', {'inputType': 'insertFromPaste'}));

            // Finally, trigger the 'Enter' key to submit the input
            propertyInput.dispatchEvent(new KeyboardEvent('keydown', { key: 'Enter' }));
            
            listViewObserver.disconnect();
          });
          
          listViewObserver.observe(referencesContainer, { subtree: true, childList: true });
          
          const addButton = references.querySelector('.wikibase-toolbar-button-add a');
          addButton.click();
        });
      });
    });

    if ( listview ) {
    	observer.observe(listview, { subtree: true, childList: true });
    }
})