简体   繁体   English

如何在chrome扩展开发中获取选定的文本?

[英]How to get selected text in chrome extension development?

I'm developing a chrome extension which involves getting selected text of the current tab. 我正在开发一个chrome扩展,它涉及获取当前选项卡的选定文本。 Here is the html file that I use: 这是我使用的html文件:

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <title></title>
        <script>
            chrome.tabs.executeScript( {
                code: "window.getSelection().toString();"
            }, function(selection) {
                document.getElementById("output").value = selection[0];
            });
        </script>
    </head>
    <body>
        <div id="output"></div>
    </body>
</html>

It doesn't work, why? 它不起作用,为什么? As followed is the error message from Chrome App & Extension Developer Tool , some of these error messages are cut with ellipses, sorry I haven't figured out how to view the full error messages here, view details only gives me the stack track, not the full error message. 以下是来自Chrome App和Extension Developer Tool的错误消息,其中一些错误消息是用省略号剪切的,抱歉我还没弄清楚如何在这里查看完整的错误消息, 查看详细信息只给出了堆栈跟踪,而不是完整的错误消息。

在此输入图像描述

As @Xan suggested, the method mentioned before (you can find it here ) is overcomplicated. 正如@Xan建议的那样,之前提到的方法(你可以在这里找到它)过于复杂。 To get it to work, there are only two things to do: 为了让它发挥作用,只有两件事要做:

  1. Change value to innerHTML in document.getElementById("output").value document.getElementById("output").value中将value更改为innerHTML document.getElementById("output").value

  2. Add an activeTab permission in manifest.json file manifest.json文件中添加activeTab权限

Here is the complete source code, three files in total. 这是完整的源代码,共有三个文件。

manifest.json 的manifest.json

{
    "manifest_version": 2,
    "name": "sample",
    "description": "A sample extension to get the selected text",
    "version": "1.0",
    "icons": { 
        "16": "img/icon16.png",
        "48": "img/icon48.png",
        "128": "img/icon128.png" 
    },
    "browser_action": {
        "default_popup": "popup.html"
    },
    "permissions": [
        "activeTab"
    ]
}

popup.html popup.html

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <script src="popup.js"></script>
        <title></title>
    </head>
    <body>
        <div id="output"></div>
    </body>
</html>

popup.js popup.js

chrome.tabs.executeScript( {
    code: "window.getSelection().toString();"
}, function(selection) {
    document.getElementById("output").innerHTML = selection[0];
});

Your original approach was correct (and probably taken from this question ). 你原来的方法是正确的(可能来自这个问题 )。

It had 2 problems: 它有两个问题:

  1. Inline scripts ( <script>...</script> ) are not allowed ; 不允许使用内联脚本( <script>...</script> ); it's fixed by putting code in a separate file, say, popup.js . 通过将代码放在一个单独的文件中来修复它,比如popup.js

  2. You need permission to access a page for content script injection; 您需要获得访问内容脚本注入页面的权限; in your particular case, there's a specific permission, "activeTab" , that does it in a transparent and painless way with no security warnings. 在您的特定情况下,有一个特定的权限, "activeTab" ,它以透明和无痛的方式执行,没有安全警告。 When your extension is invoked (by clicking on the button), you are given access to the current tab. 调用扩展时(通过单击按钮),您可以访问当前选项卡。

With those fixed, your "direct" approach works. 通过这些修复,您的“直接”方法有效。

By the way, to debug such problems in future, you need to inspect the popup page . 顺便说一下,为了将来调试这些问题,你需要检查弹出页面


As for your own answer, you are over-complicating things a lot. 至于你自己的答案,你的事情过于复杂。

You don't need an Event page is this particular case; 您不需要事件页面就是这种特殊情况; your popup can call executeScript and listen to messages. 你的弹出窗口可以调用executeScript并监听消息。 There are cases when you do need it, specifically when you can't guarantee that popup is open when content script sends messages; 还有,当需要它,特别是当你不能保证弹出窗口打开时,内容脚本发送消息的情况下, but here you can guarantee it. 但在这里你可以保证。

Supposing you need the event page, consider not using getBackgroundPage to call a method in it - it tightly couples code; 假设您需要事件页面,请考虑使用getBackgroundPage来调用其中的方法 - 它紧密地耦合代码; you can instead send a message. 你可以改为发送消息。 sendResponse can be used to pass the results back, even asynchronously . sendResponse可用于将结果传回, 甚至是异步传递。

Finally, your schema is confusing with respect to content.js . 最后,您的架构在content.js方面令人困惑。 Only one copy of it executes, in a special context that is attached to the target page (and not in the extension context). 在附加到目标页面(而不是在扩展上下文中)的特殊上下文中,只执行一个副本。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM