单击扩展图标时运行脚本

时间:2016-03-22 10:41:16

标签: google-chrome-extension google-chrome-devtools

我尝试使用此行为进行扩展:当我单击扩展按钮时,它会解析当前页面并为每个找到的项目执行一个函数。

background.js

            function downloadPage(urlpage,name){
                chrome.tabs.create({
                    url: urlpage
                }, function(tab) {
                    chrome.tabs.onUpdated.addListener(function func(tabId, changeInfo) {
                        if (tabId == tab.id && changeInfo.status == 'complete') {
                            chrome.tabs.onUpdated.removeListener(func);
                            savePage(tabId, name);
                        }
                    });
                });
            }


            function savePage(tabId, name) {
                chrome.pageCapture.saveAsMHTML({
                    tabId: tabId
                }, function(blob) {
                    var url = URL.createObjectURL(blob);
                    // Optional: chrome.tabs.remove(tabId); // to close the tab
                    chrome.downloads.download({
                        url: url,
                        filename: 'prueba/test.mht'
                    });
                });
            }

popup.js

            var candidatos = document.getElementsByClassName("user-name");

            if(candidatos != null){
                for (i = 0; i < candidatos.length; i++) {
                  chrome.extension.getBackgroundPage().downloadPage(candidatos[i].href, candidatos[i].text)             
                }

            }

的manifest.json

    {
      "manifest_version": 2,

      "name": "Test",
      "description": "Test",
      "version": "1.0",
      "author": "Pablo",
          "background": {
            "scripts": ["background.js"]
        },
      "browser_action": {
        "default_icon": "icon.png",
        "default_popup": "popup.html"
      },
      "permissions": [
        "activeTab",
        "tabs",
        "webNavigation",
        "contextMenus",
        "downloads",
        "<all_urls>",
        "pageCapture"

      ]
    }

点击扩展程序按钮后,我无法运行任何内容。

提前致谢。

2 个答案:

答案 0 :(得分:0)

更新

当我说“当我点击扩展按钮时无法运行任何东西”时,我已经在你的代码中运行了你的代码,我想你的意思是savePage函数没有被调用。这是因为在chrome.tabs.create函数的回调中,您注册了chrome.tabs.onUpdated个侦听器,为时已晚。我建议您只使用从回调中获得的标签,然后按照自己的意愿行事。

function downloadPage(urlpage,name){
    chrome.tabs.create({
        url: urlpage
    }, function(tab) {
        savePage(tab.id, name);
    });
}

建议您阅读Official Guide,尤其是browser action。基本部分应该是注册浏览器动作监听器并监听onClicked事件。

chrome.browserAction.onClicked.addListener(function () {
    // Do what you want when clicking the 'extension icon'
});

答案 1 :(得分:0)

你的根本问题是popup.js是指popup.html的DOM,它没有你需要的类或代码。为了与DOM交互,您需要一个内容脚本。最好的方法是以编程方式注入后台页面。然后你也可以使用回调参数来避免使用消息传递:

[System.Diagnostics.DebuggerStepThroughAttribute()]
    [System.CodeDom.Compiler.GeneratedCodeAttribute("System.Runtime.Serialization", "4.0.0.0")]
    [System.Runtime.Serialization.DataContractAttribute(Name="Employee", Namespace="http://schemas.datacontract.org/2004/07/WcfService1")]
    [System.SerializableAttribute()]
    public partial class Employee : object, System.Runtime.Serialization.IExtensibleDataObject, System.ComponentModel.INotifyPropertyChanged {

        [System.NonSerializedAttribute()]
        private System.Runtime.Serialization.ExtensionDataObject extensionDataField;

        [System.Runtime.Serialization.OptionalFieldAttribute()]
        private string IdField;


        [global::System.ComponentModel.BrowsableAttribute(false)]
        public System.Runtime.Serialization.ExtensionDataObject ExtensionData {
            get {
                return this.extensionDataField;
            }
            set {
                this.extensionDataField = value;
            }
        }

        [System.Runtime.Serialization.DataMemberAttribute()]
        public string Id {
            get {
                return this.IdField;
            }
            set {
                if ((object.ReferenceEquals(this.IdField, value) != true)) {
                    this.IdField = value;
                    this.RaisePropertyChanged("Id");
                }
            }
        }

@ HaibaraAi的观点是,如果弹出窗口的唯一目的是在后台触发一个动作,那么省略弹出窗口就更容易了:

chrome.tabs.query({active:true},function(tabArray){
    chrome.tabs.executeScript(tabArray[0].id,
        {code:"document.getElementsByClassName('user-name');"},
        allFrames);
});

// the parameter to allFrames is the result of code in each frame of the tab
function allFrames(frames) {
    for ( var i = 0 ; i < frames.length ; i++ ) {
        var classes = frames[i];
        for ( var j = 0 ; j < classes.length ; j++ ) {
            downloadPage(classes[j].href,classes[j].text);
        }
    }
}

由于chrome.browserAction.onClicked.addListener(function(tab) { chrome.tabs.executeScript(tab.id, {code:"document.getElementsByClassName('user-name');"}, allFrames); }); 为您提供了一个完全加载的标签,因此您无需监听其完成情况。所以我们可以坚持@ HaibaraAi的那个功能版本。因此,完成的示例是

tabs.create

使用原始chrome.browserAction.onClicked.addListener(function(tab) { chrome.tabs.executeScript(tab.id, {code:"document.getElementsByClassName('user-name');"}, allFrames); }); function allFrames(frames) { for ( var i = 0 ; i < frames.length ; i++ ) { var classes = frames[i]; for ( var j = 0 ; j < classes.length ; j++ ) { downloadPage(classes[j].href,classes[j].text); } } } function downloadPage(urlpage,name){ chrome.tabs.create({ url: urlpage }, function(tab) { savePage(tab.id, name); }); } 。而你不再需要弹出窗口。 (此外,savePage权限中包含activeTab权限,因此您不需要这样做。)

相关问题