在Chrome扩展程序中,如何打开一个标签页并在它加载完成后对其进行修改?

前端开发 2026-07-10

在研究Chrome扩展开发时,我做了一个非常简单的扩展,只包含一个按钮;点击它时,应该把Google主页的标题改成指定的内容。

只有当前标签页已经是Google首页时,我才成功让它工作。

如果不是这种情况,扩展就会打开一个新标签页,在那里加载Google首页——然后它应该修改标题。

问题在于,我无法让标题改变。

我尝试了这里描述的方案,但始终无法让它起作用: Open tab, wait for it to finish loading then close it

在我的主JavaScript文件(extension.js)中,我有:

const googleUrl = "https://www.google.com/";

function conquerGoogle (tab) {
    chrome.tabs.sendMessage(tab.id, { action : "conquer" });
}

async function openNewTabAndConquerGoogle () {
    const[tab] = await chrome.tabs.create({ url : googleUrl, active : true });

    //FIXME Does not work at all.
    chrome.tabs.onUpdated.addListener( async (tabId, changeInfo, listenedTab) => {
        if ( (tabId === tab.id) && (changeInfo.status === 'completed') ) {
            conquerGoogle(tab);
        }
    })
}

document.querySelector('button').onclick = async (e) => {
    const [tab] = await chrome.tabs.query({ active: true });

    if (tab.url === googleUrl) {
        conquerGoogle(tab);
    }
    else {
        openNewTabAndConquerGoogle()
    }
};

在content.js文件中,我只有:

chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
    if (request.action == "conquer") {
        document.title = "THIS IS MY GOOGLE NOW";
    }
});

我也尝试监听DOM加载,但仍然没有任何反应。怎么在那个新标签页里改变标题?

解决方案

请更新你的popup.js。

document.querySelector('button').onclick = async () => {
    const googleUrl = "https://www.google.com/";
    const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });

    if (tab.url === googleUrl) {
        // If already on Google, we can send the message directly
        chrome.tabs.sendMessage(tab.id, { action: "conquer" });
    } else {
        // Otherwise, tell the background script to open the tab and handle it
        chrome.runtime.sendMessage({ action: "open_and_modify", url: googleUrl });
    }
};

然后编写background.js

chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
    if (request.action === "open_and_modify") {
        createTabAndNotify(request.url);
    }
});

async function createTabAndNotify(url) {
    const tab = await chrome.tabs.create({ url, active: true });

    // Define the listener function separately so we can remove it later
    const listener = (tabId, changeInfo) => {
        if (tabId === tab.id && changeInfo.status === 'complete') {
            // 1. Remove the listener to prevent memory leaks/double-firing
            chrome.tabs.onUpdated.removeListener(listener);

            // 2. Send the message to the content script
            // Note: Sometimes the content script needs a tiny delay to register its listener
            setTimeout(() => {
                chrome.tabs.sendMessage(tabId, { action: "conquer" })
                    .catch(err => console.log("Content script not ready yet, retrying..."));
            }, 100);
        }
    };

    chrome.tabs.onUpdated.addListener(listener);
}

请检查你的manifest.json

{
  "permissions": ["tabs", "scripting"],
  "host_permissions": ["https://www.google.com/*"],
  "background": {
    "service_worker": "background.js"
  },
  "content_scripts": [
    {
      "matches": ["https://www.google.com/*"],
      "js": ["content.js"]
    }
  ]
}
站内所有文章版权归属LeftHeroAI导航站,无授权禁止任何主体转载、抄袭、复制内容,亦不得私自架设镜像站点。一经侵权,本站将通过法律途径追责。

相关文章