使用弹出窗口以编程方式注入Chrome扩展程序内容脚本

时间:2019-11-27 17:26:32

标签: javascript jquery google-chrome-extension

紧跟previous post之后,我现在尝试创建一个Chrome扩展程序版本,该版本未在content_scripts:文件中指定matches:manifest.json;而是通过从弹出窗口触发的事件以编程方式注入内容脚本,在该事件中,用户请求启用扩展,然后为执行内容脚本授予可选权限。基本原理是能够使扩展程序在具有不同顶级域名的主机的页面上运行(有关详细信息,请参见上一篇文章)。借助wOxxOm的许多出色提示,我设法创建了至少在有限的测试下有效的工具。到目前为止,唯一可见的障碍是,用户似乎不得不在内容脚本运行之前请求初始启用两次

下面是我到目前为止创建的演示版本。如果要尝试,则必须提供自己的content.js脚本。用户单击扩展图标和弹出菜单中的Enable项目。

我非常想知道整体代码是否正确,以及什么可能导致需要在内容脚本执行之前两次单击Enable弹出项。

manifest.json:

{
  "manifest_version": 2, 
  "name": "My Extension",
  "version": "0.1",
  "description": "Demo extension.",
  "background": {
              "scripts": ["background.js"],
              "persistent": false
            },
    "browser_action":{
    "default_popup": "popup.html"
  },                   
 "optional_permissions":["tabs","https://*/*"]
  }

popup.html:

<html>
<head>
<style>
ul{list-style-type:none;width:150px;}
li:hover{cursor:pointer;}
</style>
</head>
<body>
<ul id="popupmenu">
<li id="li_1">Enable</li>
</ul>
<script src="jQuery.js"></script>
<script src="popup.js"></script>
</body>
</html>

popup.js:

jQuery(function($){
  $(document).ready(function(){
    $("#li_1").click(function(){
         chrome.permissions.request({
           permissions: ['tabs'],
           origins: ["https://*/*"]
        }, function(granted) {
          if (granted) {
            chrome.runtime.sendMessage("granted");
          } else {
            alert("denied");
          }
       });
    });
  });
});

background.js:

function injectScript(tab){
  chrome.tabs.executeScript(tab,{
     file: "jQuery.js"
   }); 
   chrome.tabs.executeScript(tab,{
     file: "content.js"
   });
}

chrome.runtime.onMessage.addListener(
  function(message) {
    if(message == "granted"){
      chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
        var tabId = tabs[0].id;
        injectScript(tabId);
        chrome.permissions.contains({origins:["https://*/*"]}, function(perm) {
        if (perm) { 
          chrome.tabs.onUpdated.addListener(function(tabId){
             injectScript(tabId);
          });
        }
       });
     });
    }
  return true;
});

0 个答案:

没有答案