Chrome扩展程序中JS / HTML之间的通信

时间:2016-06-21 03:31:04

标签: javascript html google-chrome-extension

我正在尝试制作我的第一个Chrome扩展程序而没有任何先前的JS知识,我在执行此操作时遇到了一些麻烦。

扩展有什么作用?

这是一个页面操作扩展,用于生成字符串并将其复制到剪贴板。该字符串包含DOM中的某些元素属性。

范围

它仅适用于两个页面(以下域名为示例):

  1. https://xxx.abc.com/CFM/Messages/CFMEWFA/ *
  2. https://xxx.abc.com/CFM/Messages/FraudPrevention/ *
  3. 扩展程序的元素

    该扩展程序有一个 popup.html ,其中包含三个可点击的选项供用户自行选择:

    • 没有回复
    • 无效
    • 有效

    根据用户在弹出窗口中的选择格式化字符串,以及标签网址是否包含“CFMEWFA”或“FraudPrevention”。

    popup.html

    <!doctype html>
    <html>
    
    <body>
      <script src="popup.js"></script>
      <ul id="MENU">
        <li id="MENUnoResponse"><a href="#">No reponse</a>
        </li>
        <li id="MENUinValid"><a href="#">Invalid</a>
        </li>
        <li id="MENUvalid"><a href="#">Valid</a>
        </li>
      </ul>
    </body>
    
    </html>
    

    popup.js 应该在popup.html中监听点击,使用多项目点击处理程序,然后在点击时发送消息background.js。该消息应包含与popup.html中的li id对应的参数。

    popup.js

    var theParentMenu = document.querySelector("#MENU");
    theParentMenu.addEventListener("click", userHasClicked, false);
    
    function userHasClicked(e) {
      if (e.target !== e.currentTarget) {
        var clickedItem = e.target.id;
        chrome.runtime.sendMessage({
          directive: e.target.id
        }, function(response) {
          this.close();
        });
      };
      e.stopPropagation();
    }
    

    background.js 管理扩展图标的显示位置。它还会在执行 content.js 之前侦听来自popup.js的消息(包含由用户从popup.html中选择的参数),这是一个在tab.url中运行的脚本从DOM获取属性并生成字符串。我还没有开始构建content.js,因为之前在其他文件中存在未解决的问题。

    background.js

    //Displays the page action extension only on specific pages
    function checkForValidUrl(tabId, changeInfo, tab) {
    
        if (tab.url.indexOf("https://xxx.abc.com/CFM/Messages/FraudPrevention/") == 0) 
            {
            chrome.pageAction.show(tabId);
            }
        else if (tab.url.indexOf("https://xxx.abc.com/CFM/Messages/CFMEWFA/") == 0) 
            {
            chrome.pageAction.show(tabId);
            }
    };
    
    chrome.tabs.onUpdated.addListener(checkForValidUrl)
    
    
    chrome.runtime.onMessage.addListener(
        function(request, sender, sendResponse) {
            switch (request.directive) {
            case "MENUnoReponse":
                // execute the content script
                chrome.tabs.executeScript(null, { // defaults to the current tab
                    //file: "contentscript.js", // script to inject into page and run in sandbox
                    //allFrames: true // This injects script into iframes in the page.
                });
                sendResponse({}); // sending back empty response to sender
            case "MENUinValid":
                // execute the content script
                chrome.tabs.executeScript(null, { // defaults to the current tab
                    //file: "contentscript.js", // script to inject into page and run in sandbox
                    //allFrames: true // This injects script into iframes in the page.
                });
                sendResponse({}); // sending back empty response to sender
            case "MENUvalid":
                // execute the content script
                chrome.tabs.executeScript(null, { // defaults to the current tab
                    //file: "contentscript.js", // script to inject into page and run in sandbox
                    //allFrames: true // This injects script into iframes in the page.
                });
                sendResponse({}); // sending back empty response to sender
    
                break;
            default:
                // helps debug when request directive doesn't match
                alert("Unmatched request of '" + request + "' from script to background.js from " + sender);
            }
        }
    );
    

    的manifest.json

    {
      "manifest_version": 2,
    
      "name": "EW logger",
      "description": "This extension creates logs for early warning and fraud prevention cases",
      "version": "1.0",
    
      "page_action": {
        "default_title": "EW",
        "default_icon": "icon.png",
        "default_popup": "popup.html"
      },
    
    "background": {
        "scripts": ["background.js"]
    },
    
      "permissions": [
        "tabs",
        "clipboardWrite",
        "https://xxx.abc.com/*"
      ]
    
    }
    

    什么有效:

    • 扩展图标应该会显示。

    我的问题:

    • popup.html中的选项不起作用。单击时,Popup.js不执行任何操作。

    您是否有任何关于如何“正确”监听popup.html中的点击,然后向background.js发送包含参数的消息的建议?

1 个答案:

答案 0 :(得分:1)

您的脚本在加载正文之前正在运行,因此找不到该元素。您可以通过将脚本标记移动到正文的底部来解决此问题。或者,使用<script src="popup.js" defer></script>来延迟执行,直到加载dom。

https://developer.mozilla.org/en-US/docs/Web/HTML/Element/script#attr-defer

此外,您应该使用console.log(消息)和Chrome Devtools控制台来调试和检查错误。

https://developer.mozilla.org/en-US/docs/Web/API/Console/log https://developers.google.com/web/tools/chrome-devtools/

相关问题