【问题标题】:Getting selected text in a Chrome extension在 Chrome 扩展程序中获取选定的文本
【发布时间】:2021-10-03 03:36:18
【问题描述】:

我正在尝试创建一个 Chrome 扩展程序,允许用户在单击按钮后获取网页的选定文本,然后在控制台中记录此文本。

但我的代码只有在从 HTML 弹出窗口中选择文本时才有效。 如果我从一个随机网页中选择一个文本,然后单击“保存”按钮,那么控制台中会打印一个空行。

我猜我的 content.js 文件在显示扩展弹出窗口时无法与网页交互,但我不知道如何解决这个问题。我知道还有其他类似的问题,但我没有尝试过(例如在不同的 .js 文件之间传递消息)。

这是我的文件:

ma​​nifest.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"
}}

index.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>

content.js:

const saveBtn = document.getElementById("save-btn")

saveBtn.addEventListener("click", function(){
console.log(window.getSelection().toString())
})

【问题讨论】:

    标签: javascript google-chrome google-chrome-extension chrome-extension-manifest-v3


    【解决方案1】:
    1. 从 index.html 中删除 content.js。内容脚本适用于网页,而不适用于弹出窗口等扩展页面。

    2. 创建 index.js 并将其加载到 index.html 中:

        <script src="index.js"></script>
      </body>
      
    3. index.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},
            function: () => getSelection().toString(),
          });
        } catch (e) {
          return; // ignoring an unsupported page like chrome://extensions
        }
        document.body.append('Selection: ' + result);
      };
      
    4. 编辑 manifest.json 以允许在点击时在活动选项卡中注入代码:

      "permissions": ["scripting", "activeTab"]
      

    请注意,弹出窗口是一个单独的窗口,因此它有自己独立的开发工具和控制台:在弹出窗口内右键单击并在菜单中选择“检查”。

    【讨论】:

    • 感谢您的回答,它现在正在工作!只是一个问题:在新的 index.js 文件中只使用 window.getSelection() 方法是不可能的吗?是因为弹出窗口有自己的 DOM 吗? index.js中是不是无法访问网页的DOM?
    • 弹出是一个完全不同的页面。
    猜你喜欢
    • 1970-01-01
    • 2013-10-10
    • 2016-03-14
    • 2023-03-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-06
    相关资源
    最近更新 更多