可以使用 content script,在页面的 DOM 完全加载后,注入自己的 js 脚本,进行 DOM 操作。
该脚本应该等到 window.onload
或者将 DOMContentLoaded
事件作为触发的一部分触发,以确保页面的所有资源和 DOM 都已经准备好了。
示例代码:
// 注册 content script
chrome.extension.onMessage.addListener(function(request, sender, sendResponse) {
if (request.action === 'execute-dom-operation') {
// 在 DOMContentLoaded 后执行 DOM 操作
window.addEventListener('DOMContentLoaded', function() {
// 进行 DOM 操作
console.log('DOM 已准备就绪');
// 然后通知 popup
sendResponse({message: 'DOM 操作已完成'});
});
// 注意,返回 true 表示接收到异步消息,需要在回调中执行 sendResponse
return true;
}
});
content script 中的消息处理程序将会在 popup 随时发送给扩展的消息中被调用:
chrome.runtime.sendMessage({action: 'execute-dom-operation'}, function(response) {
console.log(response.message);
});