在Chrome扩展中获取选定文本

7
我正在尝试创建一个Chrome扩展程序,允许用户在单击按钮后获取网页上所选文本,然后将此文本记录在控制台中。
但是,只有在从HTML弹出窗口中选择文本时,我的代码才能正常工作。如果我从随机网页中选择文本,然后点击“保存”按钮,那么控制台将会打印一行空白行。
我猜测我的content.js文件无法在扩展程序弹出窗口显示时与网页交互,但我不知道该如何解决这个问题。我知道还有其他类似的问题,但我尝试了各种方法(例如在不同的.js文件之间进行消息传递),但都没有起作用。
以下是我的文件:
manifest.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())
})
1个回答

9
  1. Remove content.js from index.html. Content scripts are for web pages, not for extension pages such as the popup.

  2. Create index.js and load it in 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. edit manifest.json to allow code injection in the active tab on click:

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

谢谢你的回答,现在它可以工作了!只有一个问题:在新的index.js文件中,仅使用window.getSelection()方法是否不可能?这是因为弹出窗口有自己的DOM吗?在index.js中无法访问网页的DOM,这是不可能的吗? - kiaran
弹出窗口是完全不同的页面。 - wOxxOm

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接