Add Pdf, Doc, Ppt tabs to Google Search

Adds PDF, DOC, and PPT tabs to Google search results

// ==UserScript==
// @name         Add Pdf, Doc, Ppt tabs to Google Search
// @namespace    http://tampermonkey.net/
// @version      1.2
// @description  Adds PDF, DOC, and PPT tabs to Google search results
// @author       Bui Quoc Dung
// @match        *://www.google.com/search*
// @icon         https://www.google.com/favicon.ico
// @grant        none
// ==/UserScript==

(function () {
    'use strict';

    const fileTabs = [
        { label: 'Pdf', query: 'filetype:pdf' },
        { label: 'Doc', query: '(filetype:doc OR filetype:docx)' },
        { label: 'Ppt', query: '(filetype:ppt OR filetype:pptx)' },
    ];

    function addFileTabs() {
        const firstTab = document.querySelector('div[role="listitem"]');
        const tabContainer = firstTab?.parentElement;
        if (!tabContainer) return;

        const query = new URLSearchParams(window.location.search).get('q');
        if (!query) return;

        fileTabs.forEach(({ label, query: filetypeQuery }) => {
            // Avoid adding the PDF tab if it already exists
            if ([...tabContainer.querySelectorAll('a')].some(a => a.textContent.trim() === label)) return;
            if (query.toLowerCase().includes('filetype:')) return;

            const fileSearchUrl = `/search?q=${encodeURIComponent(`${query} ${filetypeQuery}`)}`;

            const tab = document.createElement('div');
            tab.setAttribute('role', 'listitem');
            tab.innerHTML = `
                <a href="${fileSearchUrl}" class="C6AK7c">
                    <div class="mXwfNd"><span class="R1QWuf">${label}</span></div>
                </a>
            `;

            const lastTab = tabContainer.querySelector('div[role="listitem"]:last-child');
            lastTab?.insertAdjacentElement('afterend', tab);
        });
    }

    // Run once on load
    addFileTabs();

    // Observe dynamic DOM changes (especially for SPA behavior)
    const observer = new MutationObserver(() => addFileTabs());
    observer.observe(document.body, { childList: true, subtree: true });
})();