我有 popup.html 和 popup.js,没有服务人员,也没有内容脚本,一切都工作正常。
现在我被要求从网站中提取用户名。该网站是一个ReactJS网站,所以它使用客户端渲染。
<ul data-v-aec73e6e="" class="ld-application-menu__list">
<li data-v-aec73e6e="" class="ld-application-menu__user type-title-3">
john Doe
</li> </ul>
我想提取 John Doe,然后将其发送到 popup.js 来执行所需的逻辑。
我想在弹出窗口打开时执行代码,我们的用户已经知道何时打开弹出窗口,因此那时 DOM 将正确加载,我已授予
activetab
和 scripting
权限。
例如,这就是服务工作者的background.js的样子(我也尝试过内容脚本)
function getUser() {
console.log("Fetching user from DOM");
const userElement = /** @type {HTMLLIElement} */ (
document.querySelector(".ld-application-menu__user")
);
if (userElement) {
const cms_user = userElement.innerText.trim();
console.log("cms_user", cms_user);
// Optionally, send the data back to the popup or background script
//chrome.runtime.sendMessage({ cms_user });
} else {
console.log("User element not found in DOM");
}
}
chrome.action.onClicked.addListener((tab) => {
chrome.scripting.executeScript({
target: { tabId: tab.id },
func: getUser,
});
});
它甚至没有显示
console.log()
,就好像脚本根本没有执行一样。
我通过使用
content_scripts
解决了这个问题,在 content.js
let cms_user = null;
// wait 1 seconds for the user element to load
setTimeout(() => {
// get the user element
const userElement = /** @type {HTMLLIElement} */ (
document.querySelector(".ld-application-menu__user")
);
if (userElement) {
cms_user = userElement.innerText.trim();
console.log("cms_user", cms_user);
// save the data in chrome storage
chrome.storage.local.set({ cms_user: cms_user });
} else {
console.log("User element not found in DOM");
}
}, 1000);
然后在
popup.js
中我从chrome存储中获取cms_user
值