2016-01-28 94 views

回答

1

請考慮使它不彈出,但與content script

這個想法是,通過點擊你的擴展的圖標腳本將插入一個表單到活動標籤的DOM。

1

您可以使用chrome.windows.createtype: "popup"製作單獨的窗口。

但是,請注意,沒有辦法讓它保持在最佳狀態。

2

要做到這一點,最好的方法是使用內容腳本插入一個自定義iframe,它將包含與常規彈出窗口相同的腳本/ html。一個iframe可以讓你隔離HTML &樣式表與現有網站的網頁交互。
iframe html文件應在manifest.json中列爲web accessible resources

當點擊瀏覽器圖標時,內容腳本將處理iframe顯示。

例如,Evernote web clipper正在使用此方法。

代碼示例,可以幫助你:

1)定義您manifest.json文件瀏覽器操作(做不表明彈出屬性),使popup.html可訪問網站:

{ 
    "name": "My extension", 
    ... 
    "browser_action": { 
     "default_icon": {      // optional 
     "19": "images/icon19.png",   // optional 
     "38": "images/icon38.png"   // optional 
     } 
    }, 
    "web_accessible_resources": ["popup.html"] 
    } 

2)創建包含彈出窗口的html & css的popup.html文件;

3)創建background.js腳本,將監聽瀏覽器操作的點擊和消息發送到內容腳本:

chrome.browserAction.onClicked.addListener(function (tab){ 
    chrome.tabs.sendMessage(tab.id, 'browser_action_click', function(callback_data) { 
     }); 
}) 

4)在你的content_script.js監聽瀏覽器操作的背景點擊郵件,顯示/隱藏iframe:

var show = false; 

var controller = { 
    insertIframe: function(){ 
    var iFrame = document.createElement("iframe"); 
    iFrame.setAttribute('style', ''); 
    iFrame.setAttribute('id', 'popup_iframe'); 
    iFrame.src = chrome.extension.getURL ("popup.html"); 
    if (document.body) { 
     //sometimes document body is not loaded yet. Just skip 
     document.body.insertBefore(iFrame, document.body.firstChild); 
    } 
    }, 
    getIframe: function() { 
    return document.getElementById('popup_iframe'); 
    }, 
    hideIframe: function() { 
    var iframe = this.getIframe(); 
    iframe.style.display = 'none'; 
    }, 
    showIframe: function() { 
    var iframe = this.getIframe(); 
    iframe.style.display = 'block'; 
    }, 
    listenForMessages: function() { 
    chrome.runtime.onMessage.addListener(function (request, sender, sendResponse) { 
     switch(request) { 
     case 'browser_action_click': 
      show = !show; 
      show ? this.showIframe() : this.hideIframe(); 
     } 
     return true; 
    }.bind(this)); 
    } 
}; 

controller.insertIframe(); 
controller.listenForMessages(); 
+0

謝謝德米特里。你可以幫助我的任何示例代碼? –

+0

@ArpanDas答案更新了一些代碼示例。 –

+0

嘿德米特里, 我試過使用這個,但不知何故,它不工作。我點擊瀏覽器按鈕,但沒有創建iFrame。 –

相關問題