Chrome扩展:如何导航到活动标签页上的页面,并在加载时调用函数

huangapple go评论58阅读模式
英文:

chrome extensions : How do I navigate to a page on the active tab, and call a function onLoad

问题

The lines

console.log("Finished loading profile page")

and

console.log("after the onUpdated event")

are never executed.

以下是未执行的行:

console.log("Finished loading profile page")

console.log("after the onUpdated event")
英文:

I need a very simple task, and it seems so hard to achieve.

I need to load a url in the active tab, and once loaded I need to call a function in content.js

I'm new to chrome extensions, so there are chances I'm drowning in a cup. What I did is that onClick on a button in my popup, I send a message to content.js to css query the page for the link, and if found click on it and wait until it's done.

My problem is that I cannot find a reliable way to react after the page ended loading.
Here's my code:

popup.js

function goToProfileDetailsPage(generateBtn) {
    generateBtn.addEventListener('click', async () => {
        try {
            const [tab] = await chrome.tabs.query({active: true, currentWindow: true});
            let [{result}] = await chrome.scripting.executeScript({
                target: {tabId: tab.id},
                func: () => {
                    const PROFILE_LINK_SELECTOR = '.feed-identity-module__actor-meta a'

                    const el = document.querySelector(PROFILE_LINK_SELECTOR);
                    if (el) el.click();
                    return !!el;
                },
            });
            if (!result) {
                alert('Please go to your linkedIn profile page before pressing the generate button')
                return
            }
            await new Promise(resolve => {
                chrome.tabs.onUpdated.addListener(async function listener(tabId, info) {
                    if (tabId === tab.id && info.status === 'complete') {
                        chrome.tabs.onUpdated.removeListener(listener);
                        console.log("Finished loading profile page")
                        await generateCvAndOpenTab(tab)
                        // [{result}] = await chrome.scripting.executeScript({
                        //     target: {tabId: tab.id},
                        //     func: generateCvAndOpenTab,
                        //     arguments:{tab}
                        // });

                        resolve();
                    }
                });
            });

        console.log( "after the onUpdated event" )

        } catch (e) {
            document.body.append(e.message);
        }
    });
}

The lines

console.log("Finished loading profile page")

and

console.log( "after the onUpdated event" )

are never executed.

答案1

得分: 0

在弹出窗口中直接使用executeScript。对于这个任务,甚至不需要使用消息。

操作弹出窗口是一个扩展页面,具有chrome-extension:// URL,因此可以使用所有已授予的chrome API。弹出窗口是一个独立的窗口,因此它有自己独立的开发工具:右键单击弹出窗口内部并选择"inspect"。

请注意,executeScript将函数/文件作为内容脚本在网页中运行,因此此代码可以直接访问网页的DOM,但不能访问弹出窗口的DOM或外部范围内的任何变量或函数。返回的值必须是JSON兼容的(字符串、数字、布尔值、null、这些类型的数组/对象),其他类型将传输为未定义或{}

英文:

Use executeScript directly in the popup.
For this task there's even no need for messages.

The action popup is an extension page, which has a chrome-extension:// URL and hence is capable of using all granted chrome API. The popup is a separate window so it has its own separate devtools: right-click inside the popup and select "inspect" in the menu.

Note that executeScript runs the function/file as a content script in the web page, so this code can access DOM of the web page directly, but it can't access DOM of the popup or any variables or functions in the outer scope. The returned value must be JSON-compatible (string, number, boolean, null, Array/Object of these types), any other types will transfer as undefined or {}.

generateBtn.addEventListener('click', async () => {
  try {
    const [tab] = await chrome.tabs.query({active: true, currentWindow: true});
    let [{result}] = await chrome.scripting.executeScript({
      target: {tabId: tab.id},
      func: () => {
        const el = document.querySelector('.feed-identity-module__actor-meta a');
        if (el) el.click();
        return !!el;
      },
    });
    if (!result) return;
    await new Promise(resolve => {
      chrome.tabs.onUpdated.addListener(function listener(tabId, info) {
        if (tabId === tab.id && info.status === 'complete') {
          chrome.tabs.onUpdated.removeListener(listener);
          resolve();
        }
      });
    });
    [{result}] = await chrome.scripting.executeScript({
      target: {tabId: tab.id},
      func: () => {
        // do something on the new page
      },
    });
  } catch (e) {
    document.body.append(e.message);
  }
});

huangapple
  • 本文由 发表于 2023年4月19日 15:59:35
  • 转载请务必保留本文链接:https://go.coder-hub.com/76052033.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定