kia*_*ran 7 javascript google-chrome google-chrome-extension chrome-extension-manifest-v3
我正在尝试创建一个 Chrome 扩展,允许用户在单击按钮后获取网页的选定文本,然后将该文本记录在控制台中。
但只有从 HTML 弹出窗口中选择文本时,我的代码才有效。如果我从随机网页中选择文本,然后单击“保存”按钮,则控制台中会打印一个空行。
我猜当显示扩展弹出窗口时,我的content.js文件无法与网页交互,但我不知道如何解决这个问题。我知道还有其他类似的问题,但我尝试过的任何方法(例如在不同 .js 文件之间传递消息)都不起作用。
这是我的文件:
清单.json:
{
"manifest_version": 3,
"version": "1.0",
"name": "test",
"action": {
"default_popup": "index.html"
},
"permissions": [
"tabs",
"notifications"
],
"content_scripts": [
{ "matches": ["<all_urls>"],
"js" : ["content.js"]}
],
"background":
{
"service_worker": "background.js"
}}
Run Code Online (Sandbox Code Playgroud)
索引.html:
<html>
<head>
<link rel="stylesheet" href="index.css">
</head>
<body>
<p>Just some text.</p>
<button id="save-btn">SAVE SELECTION</button>
<script src="content.js"></script>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)
内容.js:
const saveBtn = document.getElementById("save-btn")
saveBtn.addEventListener("click", function(){
console.log(window.getSelection().toString())
})
Run Code Online (Sandbox Code Playgroud)
wOx*_*xOm 10
从index.html 中删除content.js。内容脚本适用于网页,不适用于弹出窗口等扩展页面。
创建index.js并将其加载到index.html中:
<script src="index.js"></script>
</body>
Run Code Online (Sandbox Code Playgroud)
索引.js:
document.getElementById("save-btn").onclick = async () => {
const [tab] = await chrome.tabs.query({active: true, currentWindow: true});
let result;
try {
[{result}] = await chrome.scripting.executeScript({
target: {tabId: tab.id},
func: () => getSelection().toString(),
});
} catch (e) {
return; // ignoring an unsupported page like chrome://extensions
}
document.body.append('Selection: ' + result);
};
Run Code Online (Sandbox Code Playgroud)
编辑manifest.json以允许在单击时在活动选项卡中注入代码:
"permissions": ["scripting", "activeTab"]
Run Code Online (Sandbox Code Playgroud)
请注意,弹出窗口是一个单独的窗口,因此它有自己单独的开发工具和控制台:在弹出窗口内右键单击,然后在菜单中选择“检查”。