簡體   English   中英

Chrome擴展程序:更改Chrome彈出窗口的html

[英]Chrome Extension: Changing html of a chrome popup window

我做了一個Chrome擴展程序來生成任何文檔的摘要。我添加了使用瀏覽器操作圖標打開彈出窗口的功能,現在我想使用上下文菜單右鍵單擊操作來添加相同的功能。

現在,當使用windows.create()打開popup2.html時,該窗口將按原樣打開,並且沒有消息發送到popup.js腳本,並且依次發送我在background.js中打開的彈出窗口的innerHtml 。腳本未修改。

我嘗試使用chrome.tabs.sendMessage方法將消息發送到彈出窗口,但無法在此處更改其html。

background.js

chrome.runtime.onInstalled.addListener(function() {
  var context = "selection";
  var title = "See the Gist";
  var id = chrome.contextMenus.create({"title": title, "contexts":[context],"id": "context_selection"});  
});

var open_window_ids=[]

function getSummary(selected) {

    var jsonData;

    $.ajax({
        url: 'http://127.0.0.1:5000/api/summarize',
        type: 'POST',
        data: JSON.stringify(selected),
        contentType: 'application/json; charset=utf-8',
        dataType: 'json',
        async: false,
        success: function(data) {
            jsonData = data;
        }
    });

    return jsonData;
}

console.log("Booting");

chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {

    var activeTab = tabs[0];
    chrome.tabs.sendMessage(activeTab.id, {"message": "get_selected_text"}, function(response) {
        console.log('From button');
        if (response.selected_text == "") {
            document.body.innerHTML += "<h3 style='text-align: center'>No text selected! Select text and try again.</h3>";
        }
        else {
            var apiResponse = getSummary(response);
            console.log(apiResponse);
            if (!apiResponse)
            {
                document.getElementById("header").innerHTML += "<h3 class='heading'>API response unavailable.</h3>";
            }
            var summary_final = apiResponse.sentences;
            if (summary_final.length == 0) {
                document.getElementById("header").innerHTML += "<h3 class='heading'>Not enough text selected to generate summary. Select larger block of text and try again.</h3>";
                document.getElementById("footer").innerHTML += "<div style='padding:15px;'>Powered by <a href='http://zippybots.com' target='_blank'><span id='link'>Zippybots</span></a></div>";
            }
            else{
                document.getElementById("header").innerHTML += "<h1 class='heading'>The Gist is.....</h1>";
                var para = "";
                for (var i = 0;i<summary_final.length;i++)
                {
                    para += summary_final[i]+" ";
                    if( i % 3 == 2) 
                    {
                        document.getElementById("summary").innerHTML += "<p class='point'>"+para+"</p>";    
                        para = "";
                    }
                }
                if (para) document.getElementById("summary").innerHTML += "<p class='point'>"+para+"</p>";
                document.getElementById("footer").innerHTML += "<div style='padding:15px;'>Powered by <a href='http://zippybots.com' target='_blank'><span id='link'>Zippybots</span></a></div>";
            }
        }
    });
});


chrome.contextMenus.onClicked.addListener(function(info, tab){
    if (info.menuItemId == "context_selection") {
        for (var i = open_window_ids.length - 1; i >= 0; i--) {
            chrome.windows.remove(open_window_ids[i],function(){});
            open_window_ids.pop();
        }   
            // window.document.body.innerHTML += doc;
        var activeTab;
        chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
            activeTab = tabs[0];
            chrome.windows.create({url: 'popup2.html',focused:true,type:'popup'},function(win){
                open_window_ids.push(win.id);
                displayCurrent(open_window_ids[0],activeTab.id,win);
            });
        });
    }
});

function displayCurrent(id,activeTabId,popupwindow){
    console.log("Got selection tab id :"+activeTabId);
    var popupTabId = popupwindow.tabs[0].id;
    console.log("Got popup tab id :"+popupTabId);

    chrome.tabs.sendMessage(activeTabId, {"message": "get_selected_text"}, function(response) {

        console.log("Resp:"+response.selected_text);
        if (response.selected_text == "") {
            console.log("Selected text is null");
            chrome.tabs.sendMessage(popupTabId,{"message":"no_text_selected"},function (response){});
        }
        else {
            var apiResponse = getSummary(response);
            if (!apiResponse)
            {
                document.getElementById("header").innerHTML += "<h3 class='heading'>API response unavailable.</h3>";
            }
            var summary_final = apiResponse.sentences;
            if (summary_final.length == 0) {
                console.log("Summary length 0");
                chrome.tabs.sendMessage(popupTabId,{"message":"not_enough_text"},function (response){});
            }
            else {
                console.log("Summary there");
                chrome.tabs.sendMessage(popupTabId,{"message":"summary","data":summary_final},function (response){});   
            }
        }   
    });
}

popup2.html

<html>
    <head>
        <meta charset="utf-8">
        <link href="bootstrap.min.css" rel="stylesheet">
        <script src="jquery-3.1.1.min.js"></script>
        <script src="bootstrap.min.js"></script>
        <!-- <script src="api-keys.js"/></script> -->
        <link href="https://fonts.googleapis.com/css?family=Ubuntu" rel="stylesheet">
        <script type="text/javascript" src="popup.js"></script>
        <script type="text/javascript" src="background.js"></script>
        <style>
            body{
                min-width: 750px;
                font-family: 'Ubuntu', sans-serif;
                background: #f1f1f1;
                /*background: #2c001e;*/
            }
            #header{
                /*background: #dd4814;*/
                background: #2c001e;
                /*color: #dd4814;*/
                color: #fff;
                text-align: center;
                padding: 1px;
            }
            #footer{
                /*background: #dd4814;*/
                background: #2c001e;
                color: #fff;
                text-align: right;
                min-height: 50px; 
            }
            #link{
                /*color: #fff;              */
                color: #dd4814;
            }
            .point{
                color: #333;                
                /*background: #2c001e;*/
                background: #f1f1f1;
                text-align: justify;
                padding: 5px;
            }
            #summary{
                background: #f1f1f1;
                /*background: #2c001e;*/
                max-width: 720px;
                font-weight: 300;   
                font-size:15px;
                font-family: Ubuntu, Arial, "libra sans", sans-serif;
                padding-left: 30px;
            }
            .heading{
                margin-top: 10px;
                margin-bottom: 10px;
            }
        </style>
    </head>
    <body>
            <div id="header"></div>
            <!-- This will be populated when extension button is clicked -->
            <div id="summary"><br></div>
            <div id="footer">

            </div>
    </body>
</html>

content.js

console.log("Content file loaded");
chrome.runtime.onMessage.addListener( function(request, sender, sendResponse) {
    if (request.message == "get_selected_text") {
        var selectedText = document.getSelection().toString();
        sendResponse({selected_text: selectedText});
        return true;
    }
});

的manifest.json

{
  "manifest_version": 2,
  "name": "Selection Summarizer",
  "description": "A chrome extension that allows users to get a summary of a news article or large block of text.",
  "version": "1.0",
  "content_scripts": [
    {
      "matches": [
        "<all_urls>"
      ],

      "js": ["jquery-3.1.1.min.js", "content.js","popup.js"]

    }
  ],

  "background": {
        "scripts": ["background.js"],
        "persistent" :false
    },


  "browser_action": {
    "default_icon": "icon.png",
    "default_popup": "popup.html",
    "default_title": "Summarize!"
  },

  "icons": { "16": "icons/icon16.png",
           "48": "icons/icon48.png",
          "128": "icons/icon128.png" },

  "permissions": ["activeTab", "tabs","contextMenus",
    "http://127.0.0.1:5000/*","https://en.wikipedia.org/*"]
}

popup.js

chrome.runtime.onMessage.addListener( function(request, sender, sendResponse) {
    if (request.message == "no_text_selected") {
        console.log("no_text_selected");
        document.body.innerHTML += "<h3 style='text-align: center'>No text selected! Select text and try again.</h3>";
    }

    else if (request.message == "not_enough_text") {
        console.log("not enough text");
        document.getElementById("header").innerHTML += "<h3 class='heading'>Not enough text selected to generate summary. Select larger block of text and try again.</h3>";
        document.getElementById("footer").innerHTML += "<div style='padding:15px;'>Powered by <a href='http://zippybots.com' target='_blank'><span id='link'>Zippybots</span></a></div>";
    }

    else if (request.message == "summary") {
        console.log("Summary printing");
        var summary_final = request.data;
        console.log(summary_final);
        document.getElementById("header").innerHTML += "<h1 class='heading'>Summary</h1>";
        var para = "";
        for (var i = 0;i<summary_final.length;i++)
        {
            para += summary_final[i]+" ";
            if( i % 3 == 2) 
            {
                document.getElementById("summary").innerHTML += "<p class='point'>"+para+"</p>";    
                para = "";
            }
        }
        if (para) document.getElementById("summary").innerHTML += "<p class='point'>"+para+"</p>";
        document.getElementById("footer").innerHTML += "<div style='padding:15px;'>Powered by <a href='http://zippybots.com' target='_blank'><span id='link'>Zippybots</span></a></div>";
    }
    return true;
});

content.js

console.log("Content file loaded");
chrome.runtime.onMessage.addListener( function(request, sender, sendResponse) {
    if (request.message == "get_selected_text") {
        var selectedText = document.getSelection().toString();
        sendResponse({selected_text: selectedText});
        return true;
    }
});

popup.html

<html>
    <head>
        <meta charset="utf-8">
        <link href="bootstrap.min.css" rel="stylesheet">
        <script src="jquery-3.1.1.min.js"></script>
        <script src="bootstrap.min.js"></script>
        <!-- <script src="api-keys.js"/></script> -->
        <link href="https://fonts.googleapis.com/css?family=Ubuntu" rel="stylesheet">
        <script type="text/javascript" src="content.js"></script>
        <script type="text/javascript" src="background.js"></script>
        <style>
            body{
                min-width: 550px;
                font-family: 'Ubuntu', sans-serif;
                background: #f1f1f1;
                /*background: #2c001e;*/
            }
            #header{
                /*background: #dd4814;*/
                background: #2c001e;
                /*color: #dd4814;*/
                color: #fff;
                text-align: center;
                padding: 1px;
            }
            #footer{
                /*background: #dd4814;*/
                background: #2c001e;
                color: #fff;
                text-align: right;
                min-height: 50px; 
            }
            #link{
                /*color: #fff;              */
                color: #dd4814;
            }
            .point{
                color: #333;                
                /*background: #2c001e;*/
                background: #f1f1f1;
                text-align: justify;
                padding: 5px;
            }
            #summary{
                background: #f1f1f1;
                /*background: #2c001e;*/
                max-width: 720px;
                font-weight: 300;   
                font-size:15px;
                font-family: Ubuntu, Arial, "libra sans", sans-serif;
                padding-left: 30px;
            }
            .heading{
                margin-top: 10px;
                margin-bottom: 10px;
            }
        </style>
    </head>
    <body>
            <div id="header"></div>
            <!-- This will be populated when extension button is clicked -->
            <div id="summary"><br></div>
            <div id="footer">

            </div>
    </body>
</html>

您有兩個問題:

第一個問題

嘗試與已打開的彈出窗口中的腳本進行通信時,正在使用tabs.sendMessage() 作為擴展中包含的HTML頁面,該頁面中的腳本在后台上下文中運行。 因此, tabs.sendMessage()將無法與該腳本進行通信。 如果要發送該類型的消息,則需要使用runtime.sendMessage() 您可以通過多種方式在后台上下文中的腳本之間進行通信。 有關更詳細的討論,請參閱在后台上下文中的腳本之間進行通信(后台腳本,瀏覽器操作,頁面操作,選項頁面等)。

第二個問題

您正在嘗試在windows.create()回調中立即打開的窗口中將消息發送到popup.js腳本。 在運行回調時,已經開始創建窗口並分配了windowId ,但是該窗口的內容尚不存在(即尚未構建DOM且popup.js中的代碼尚未建立)已運行)。 因此,沒有偵聽器處於活動狀態,這導致未接收到消息。

解決方案

解決這些問題的簡單方法是:

  1. 在調用windows.open()之前將數據storage.localstorage.local中,並讓popup.js代碼在首次運行時從storage.local獲取它,或者
  2. 通過從popup.js代碼向您的background.js發送一條消息(使用runtime.sendMessage() )來請求數據, 從而開始從popup.js傳輸數據。 然后,您的background.js可以使用runtime.onMessage()提供的sendResponse函數將數據發送回去。
  3. 將數據存儲在background.js中的變量中,該變量可從全局范圍訪問。 在使用chrome.extension.getBackgroundPage()獲得背景的window對象之后,您的popup.js代碼即可直接訪問該范圍內的變量。

也可以等待從background.js發送消息,直到popup.js運行之后,但這可以是:A)更復雜,B)與從彈出窗口啟動runtime.sendMessage()有效地相同,或C)不保證實際運行popup.js之后(例如,僅使用setTimeout() )。

暫無
暫無

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

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