Quería jugar con el desarrollo de Chrome Extension y pensé en hacer una extensión v3 simple donde, si se hace clic en el ícono, el contenido de un elemento html en particular se registrará en la consola. Sin embargo, cuando hago clic en el ícono, obtuve null .
Lo que tengo hasta ahora:
manifiesto.json
{ "name": "Test Chrome Extension", "description": "Some test extension", "version": "1.0.0", "manifest_version": 3, "action": { "default_title": "Log the content of #someElement to the console" }, "background": { "service_worker": "background.js" }, "permissions": [ "tabs", "scripting" ], "host_permissions": [ "https://*/*", "http://*/*" ] }fondo.js
chrome.action.onClicked.addListener(execScript); async function execScript() { const tabId = await getTabId(); chrome.scripting.executeScript({ target: {tabId: tabId}, files: ['mycode.js'] }) } async function getTabId() { const tabs = await chrome.tabs.query({active: true, currentWindow: true}); return (tabs.length > 0) ? tabs[0].id : null; }micódigo.js
(function() { console.log('yes'); // this one works console.log(document.querySelector("#someElement").innerHTML); // this doesn't and returns null })();Y la página html en la que intenté hacer clic en el icono de la extensión tiene el siguiente contenido:
<body> <!-- some html content --> <div id="someElement"> <h2>Hello World</h2> <p>Lorem Ipsum text</p> </div> <!-- some html content --> </body>Entonces fue simplemente porque el elemento html estaba dentro de un iframe. Gracias a @wOxxOm por señalarlo en los comentarios.
Lo arreglé cambiando mycode.js a:
(function() { const iframeElement = document.querySelector("#iframeId"); const iframeCont = iframeElement.contentWindow || iframeElement.contentDocument; const iframeDoc = iframeContent.document ? iframeContent.document : iframeContent; console.log(iframeDoc.querySelector('#someElement').innerHTML); })();