0

I'm currently trying to make an extension for Firefox and Chrome where it converts any time in the page from 12hr to 24hr format. I have the code written but on the sites I've tested, it usually doesn't update anything, despite the console showing the times as having been. There have been a few instances where some nodes were updated, but not all of them and it isn't consistent.

"content_scripts": [
    {
        "matches": [
            "<all_urls>"
        ],
        "js": [
            "content_script.js"
        ],
        "run_at": "document_idle",
        "all_frames": true
    }
]
const tags = ['p', 'div', 'span', 
        'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 
        'strong', 'em', 'blockquote', 
        'li', 'td', 'dt', 'dd'];

const queryStr = tags.join(', ');
const nodes = document.querySelectorAll(queryStr);

setTimeout(() => {
        processNodes();
}, 2500)
const processNodes = () => nodes.forEach((node, i) => {
        if (node.innerHTML.match(/((1[0-2]|0?[1-9])(:|h)([0-5][0-9]) ?([AaPp][Mm]))/)) {
                console.log('==========');
                console.log('Before: ');
                console.log(node.innerHTML);
                node.innerHTML = node.innerHTML.replace(/((1[0-2]|0?[1-9])(:|h)([0-5][0-9]) ?([AaPp][Mm]))/, (match) => {
                        const phase = match.substring(match.length - 2, match.length).toUpperCase();
                        const hSeperator = match.includes('h');
                        match = match.replace(/[AaPp][mM]/, '');
                        const hmArray = match.split(/:|h/).map(str => Number(str));
                        const military = hmArray[0] + (phase === 'PM' && hmArray[0] < 12 ? 12 : 0);
                        return `${military < 10 ? '0' + military : military}${hSeperator ? 'h' : ':'}${hmArray[1] < 10 ? '0' + hmArray[1] : hmArray[1]}`
                })
                console.log('After: ');
                console.log(node.innerHTML);
                console.log('==========')
        }
});
Jim
  • 143
  • 3
  • 11
  • Modern sites build themselves using JavaScript which runs asynchronously after the content scripts have already run. It may take more than those 2500ms of timeout you're using. The solution is to use MutationObserver ([example](https://stackoverflow.com/a/39334319)). Also don't ever modify `innerHTML` of the page because you're breaking all event listeners attached from JavaScript ([example](https://stackoverflow.com/a/7275856) of doing it correctly). – wOxxOm Oct 22 '20 at 05:10
  • Thank you for pointing those out @wOxxOm! I managed to get it to work using a combination of those two sources. – Jim Oct 24 '20 at 16:19

0 Answers0