UNPKG

browser-plugin-creator

Version:

A modern scaffolding tool for creating browser extensions with ease

62 lines (56 loc) 1.61 kB
// 内容脚本 - 与页面交互 console.log('{{name}} DevTools内容脚本已加载'); // 监听页面变化 let observer; // 初始化观察器 function initObserver() { observer = new MutationObserver((mutations) => { mutations.forEach((mutation) => { if (mutation.type === 'childList' && mutation.addedNodes.length > 0) { // 通知DevTools面板有新元素添加 chrome.runtime.sendMessage({ type: 'DOM_CHANGED', data: { added: mutation.addedNodes.length, target: mutation.target.tagName } }); } }); }); observer.observe(document.body, { childList: true, subtree: true }); } // 页面加载完成后初始化 if (document.readyState === 'loading') { document.addEventListener('DOMContentLoaded', initObserver); } else { initObserver(); } // 监听来自后台脚本的消息 chrome.runtime.onMessage.addListener((request, sender, sendResponse) => { if (request.type === 'GET_ELEMENT_INFO') { const element = document.querySelector(request.selector); if (element) { const info = { tagName: element.tagName, id: element.id, className: element.className, textContent: element.textContent?.substring(0, 100), attributes: Array.from(element.attributes).reduce((acc, attr) => { acc[attr.name] = attr.value; return acc; }, {}) }; sendResponse(info); } } }); // 页面卸载时清理 window.addEventListener('beforeunload', () => { if (observer) { observer.disconnect(); } });