代码之家  ›  专栏  ›  技术社区  ›  GorvGoyl

调用注入。弹出窗口中的js方法。js chrome扩展

  •  2
  • GorvGoyl  · 技术社区  · 8 年前

    我正在构建一个修改页面DOM的chrome扩展。 我注射了 inject.js 而且效果很好。
    显示:

    "manifest_version": 2,
    "web_accessible_resources": ["js/inject.js"],
    "content_security_policy": "script-src 'self'  'unsafe-eval'; object-src 'self'",
    "background": { "scripts": ["js/background.js"] },
      "content_scripts" :[
        {
          "matches" : [
            "*://*.somesite.com/*"
          ],
          "js" : ["js/page.js"],
          "run_at" : "document_idle"
    
        }
      ],
    "page_action": {
        "default_icon": {                    
          "16": "images/icon16.png",           
          "24": "images/icon24.png",           
          "32": "images/icon32.png"            
        },
        "default_title": "some name",      
        "default_popup": "popup.html"   
      }
    

    页js公司:

    chrome.runtime.sendMessage({type:'showPageAction'});
    var s = document.createElement('script');
    // TODO: add "script.js" to web_accessible_resources in manifest.json
    s.src = chrome.extension.getURL('js/inject.js');
    s.onload = function() {
        this.remove();
    };
    (document.head || document.documentElement).appendChild(s);
    

    出身背景js公司:

    chrome.runtime.onMessage.addListener(function(message,sender,sendResponse){
        if(message.type === 'showPageAction'){
            chrome.pageAction.show(sender.tab.id);
        }
    });
    

    现在我也有 popup.html , popup.js 弹出页面中有一个复选框。 单击复选框应调用中的函数 注射js公司 但我无法做到这一点。

    我也试过了 location.href="javascript:disableFeature(); void 0"; 但是chrome拒绝了内联JS。

    1 回复  |  直到 8 年前
        1
  •  1
  •   GorvGoyl    8 年前

    多亏了@wOxxOm,我才能够在inject中调用方法。弹出窗口中的js。js。
    下面是示例代码。

    弹出窗口。js公司

    // event is triggered in inject.js whenever below code is run
    chrome.tabs.query({ active: true, currentWindow: true }, function (tabs) {
                chrome.tabs.sendMessage(tabs[0].id, { method: "enableFeature" }, function (response) {
                });
            });
    

    页js/内容。js公司

    chrome.runtime.onMessage.addListener(
        function (request, sender, sendResponse) {
            var evt = document.createEvent("CustomEvent");
            evt.initCustomEvent(request.method, true, true);
            document.dispatchEvent(evt);
        });
    

    注射js公司

    document.addEventListener('enableFeature', function (e)
    {
      // add your code here
    });