来自 chrome 扩展程序中内容脚本的未定义响应

Undefined response from content script in chrome extension

本文关键字:脚本 未定义 响应 chrome 扩展 程序 来自      更新时间:2023-09-26

我无法从内容脚本获得响应以显示在我的弹出窗口中.html。当此代码运行时,单击查找按钮时,将打印"来自响应的你好!",但变量响应将打印为未定义。最终目标是将当前选项卡的 DOM 放入我的脚本文件中,以便我可以解析它。我正在使用内容脚本的单次消息来获取 DOM,但它没有返回并且显示为未定义。我正在寻找任何可能的帮助。谢谢。

弹出窗口.html:

<!DOCTYPE html>
<html>
    <body>
        <head>
        <script src="script.js"></script>
        </head>
        <form >
            Find: <input id="find" type="text"> </input>
        </form>
        <button id="find_button"> Find </button>
    </body>
</html>

manifest.json:

{
    "name": "Enhanced Find",
    "version": "1.0",
    "manifest_version": 2,
    "description": "Ctrl+F, but better",
    "browser_action": {
        "default_icon": "icon.png", 
        "default_popup": "popup.html"
    },
    "permissions": [
        "tabs",
        "*://*/*"
    ],
    "background":{
        "scripts": ["script.js"],
        "persistent": true
    },
    "content_scripts":[
        {
            "matches": ["http://*/*", "https://*/*"],
            "js": ["content_script.js"],
            "run_at": "document_end"
        }
   ]
}

脚本.js:

var bkg = chrome.extension.getBackgroundPage();

function eventHandler(){
    var input = document.getElementById("find");
    var text = input.value;
    chrome.tabs.query({active: true, currentWindow: true}, function(tabs){
        var tab = tabs[0];
        var url = tab.url;
        chrome.tabs.sendMessage(tab.id, {method: "getDocuments"}, function(response){
            bkg.console.log("Hello from response!");
            bkg.console.log(response);
        });
    });
}

content_script.js:

var bkg = chrome.extension.getBackgroundPage();
chrome.runtime.onMessage.addListener(function(request, sender, sendResponse){
    if(request.method == "getDOM"){
        sendResponse({data : bkg.document});
    }else{
        sendResponse({});
    }
});

你的代码有很多问题(见我上面的评论)。


首先提出一些建议/注意事项:

  • 不要将内容脚本注入所有网页。以编程方式注入,并且仅在用户想要搜索时注入。

  • 内容脚本中进行"搜索"可能是一个更好的主意,您可以在其中直接访问 DOM 并可以对其进行操作(例如突出显示搜索结果等)。如果采用此方法,您可能需要调整权限,但始终尝试将其保持在最低限度(例如,不要在activeTab足够的情况下使用tabs等)。

  • 请记住,一旦弹出窗口关闭/隐藏(例如,选项卡获得焦点),在弹出窗口上下文中执行的所有 JS 都将中止。

  • 如果你想要某种持久性(甚至是暂时的),例如记住最近的结果或最后一个搜索词,你可以使用chrome.storagelocalStorage之类的东西。


最后,来自我的扩展演示版本的示例代码:

扩展文件组织:

          extension-root-directory/
           |
           |_____fg/
           |      |_____content.js
           |
           |_____popup/
           |      |_____popup.html
           |      |_____popup.js
           |
           |_____manifest.json

manifest.json:

{
    "manifest_version": 2,
    "name":    "Test Extension",
    "version": "0.0",
    "offline_enabled": true,
    "content_scripts": [
        {
            "matches": [
                "http://*/*",
                "https://*/*"
            ],
            "js":     ["fg/content.js"],
            "run_at": "document_end",
        }
    ],
    "browser_action": {
        "default_title": "Test Extension",
        "default_popup": "popup/popup.html"
    }
}

内容.js:

// Listen for message...
chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
    // If the request asks for the DOM content...
    if (request.method && (request.method === "getDOM")) {
        // ...send back the content of the <html> element
        // (Note: You can't send back the current '#document',
        //  because it is recognised as a circular object and 
        //  cannot be converted to a JSON string.)
        var html = document.all[0];
        sendResponse({ "htmlContent": html.innerHTML });
    }
});

弹出窗口.html:

<!DOCTYPE html>
<html>
    <head>
        <script type="text/javascript" src="popup.js"></script>
    </head>
    <body>
        Search:
        <input type="text" id="search" />
        <input type="button" id="searchBtn" value=" Find "
               style="width:100%;" />
    </body>
</html>

弹出窗口.js:

window.addEventListener("DOMContentLoaded", function() {
    var inp = document.getElementById("search");
    var btn = document.getElementById("searchBtn");
    btn.addEventListener("click", function() {
        var searchTerm = inp.value;
        if (!inp.value) {
            alert("Please, enter a term to search for !");
        } else {
            // Get the active tab
            chrome.tabs.query({
                active: true,
                currentWindow: true
            }, function(tabs) {
                // If there is an active tab...
                if (tabs.length > 0) {
                    // ...send a message requesting the DOM...
                    chrome.tabs.sendMessage(tabs[0].id, {
                        method: "getDOM"
                    }, function(response) {
                        if (chrome.runtime.lastError) {
                            // An error occurred :(
                            console.log("ERROR: ", chrome.runtime.lastError);
                        } else {
                            // Do something useful with the HTML content
                            console.log([
                                "<html>", 
                                response.htmlContent, 
                                "</html>"
                            ].join("'n"));
                        }
                    });
                }
            });
        }
    });
});