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

use*_*018 6 javascript message google-chrome google-chrome-extension content-script

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

popup.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>
Run Code Online (Sandbox Code Playgroud)

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"
        }
   ]
}
Run Code Online (Sandbox Code Playgroud)

的script.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);
        });

    });
}
Run Code Online (Sandbox Code Playgroud)

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({});
    }
});
Run Code Online (Sandbox Code Playgroud)

gka*_*pak 18

您的代码存在很多问题(请参阅上面的评论).


一些建议/考虑因素首先:

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

  • 在内容脚本中执行"搜索"权限可能是一个更好的主意,在该脚本中您可以直接访问DOM并可以对其进行操作(例如,突出显示搜索结果等).如果你采用这种方法,你可能需要调整你的权限,但总是尽量将它们保持在最低限度(例如,不要使用tabs哪里activeTab就足够了等).

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

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


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

扩展文件组织:

          extension-root-directory/
           |
           |_____fg/
           |      |_____content.js
           |
           |_____popup/
           |      |_____popup.html
           |      |_____popup.js
           |
           |_____manifest.json
Run Code Online (Sandbox Code Playgroud)

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"
    }
}
Run Code Online (Sandbox Code Playgroud)

content.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 });
    }
});
Run Code Online (Sandbox Code Playgroud)

popup.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>
Run Code Online (Sandbox Code Playgroud)

popup.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"));
                        }
                    });
                }
            });
        }
    });
});
Run Code Online (Sandbox Code Playgroud)