我想擺弄 Chrome 擴展程式的開發,并認為我會制作一個簡單的 v3 擴展程式,如果單擊圖示,特定 html 元素的內容將被記錄到控制臺。但是,當我單擊該圖示時,我得到了null.
到目前為止我所擁有的:
清單檔案.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://*/*"
]
}
背景.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;
}
我的代碼.js
(function() {
console.log('yes'); // this one works
console.log(document.querySelector("#someElement").innerHTML); // this doesn't and returns null
})();
我嘗試單擊擴展圖示的 html 頁面具有以下內容:
<body>
<!-- some html content -->
<div id="someElement">
<h2>Hello World</h2>
<p>Lorem Ipsum text</p>
</div>
<!-- some html content -->
</body>
uj5u.com熱心網友回復:
所以這僅僅是因為 html 元素在 iframe 內。感謝@wOxxOm 在評論中指出這一點。
我通過更改mycode.js為:
(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);
})();
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/398739.html
