Add PDF Tab to Google Search

Adds a PDF tab to Google search results

当前为 2025-06-20 提交的版本,查看 最新版本

// ==UserScript==
// @name         Add PDF Tab to Google Search
// @namespace    http://tampermonkey.net/
// @version      1.1
// @description  Adds a PDF tab 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';

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

        // Avoid adding the PDF tab if it already exists
        if ([...tabContainer.querySelectorAll('a')].some(a => a.textContent.trim() === 'PDF')) return;

        const query = new URLSearchParams(window.location.search).get('q');
        if (!query || query.toLowerCase().includes('filetype:pdf')) return;

        const pdfSearchUrl = `/search?q=${encodeURIComponent(query)}+filetype:pdf`;

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

        // Insert the new tab after the last existing tab
        const lastTab = tabContainer.querySelector('div[role="listitem"]:last-child');
        lastTab?.insertAdjacentElement('afterend', pdfTab);
    }

    // Initial run
    addPDFTab();

    // Observe DOM changes in case Google dynamically modifies the tab bar
    const observer = new MutationObserver(() => addPDFTab());
    observer.observe(document.body, { childList: true, subtree: true });
})();