簡體   English   中英

來自chrome擴展中的內容腳本的未定義響應

[英]Undefined response from content script in chrome extension

我無法從我的內容腳本中獲得響應以顯示在我的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>

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"
        }
   ]
}

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

    });
}

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"
    }
}

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 });
    }
});

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>

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"));
                        }
                    });
                }
            });
        }
    });
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM