March 13, 2024

Confluence Numbered Headings in Chrome Extension

Following-up on a previous post (that was using a poor approach with bookmarklets), I share a better solution to number headings in Confluence using a Chrome Extension.

Implementation

The main challenge was to find out how to inject a Javascript in a page that uses Jquery.

Manifest

In the manifest.json you need to provide permissions to run scripts and add contextMenus as well as to access the activeTab:
"permissions": ["storage","contextMenus","scripting","activeTab"],

Background.js

In the background.js, you need to add the ContextMenus. 

Example for adding the numbers:

chrome.contextMenus.create({
    title: "Numbered Headings: Add Numbers",
    id: "numheading_add",
    contexts:["page","frame","selection","link","editable"],
    "documentUrlPatterns": ["https://*.atlassian.net/wiki/*/edit-v2/*","https://*.atlassian.net/wiki/*/edit/*" ]
});

Note that the Context menu will only be visible for Confluence pages in edit mode as specified in the documentUrlPatterns ContextMenu property.

In Background.js add also the Listener for the Contextmenu like this:

// Add Context Menu listener
chrome.contextMenus.onClicked.addListener(function(info, tab) {
    switch (info.menuItemId) {
        case "numheading_add":
            chrome.tabs.query({active: true,currentWindow: true}, function(tabs) {
                chrome.scripting.executeScript({
                    target: { tabId: tabs[0].id },
                    files: ["jquery-3.7.1.min.js","numheading_add.js"]
                });
            })
            return;
        default:
            return
                     
    } // end switch

});

This will inject a js script in the current tab using chrome.scripting.executeScript().

Script to inject

The Script to inject is called in the Context Menu listener.
See numheading_add.js in GitHub
(This is the same script as for the bookmarklet approach.)

Jquery

As you see in the ContextMenu Listener, you also need to provide jquery as js file to be run before the injected script.

Usage

This is implemented in my Confluence Chrome extension that you can get in GitHub here.

In a Confluence page open in edit mode, right-mouse click on the page to open the context menu.

You will find the extension context menu under "Confluence" and under this menu the additional entries to Add and Remove numbers in Headings.

See also


No comments:

Post a Comment