在制作Chrome插件的過程中,我使用Content Scripts注入到當前頁中,想實現當點擊頁面的按鈕后關閉當前頁面(tab)。
習慣性調用:window.close(),結果報錯:Scripts may close only the windows that were opened by it
。
好吧,google之,網友提供了以下方法:
window.opener = null; | |
window.open('','_self'); | |
window.close(); |
經嘗試依然報錯無效,就算使用了所謂的hack,即
window.open(' ','_self'); |
加多了一個空格之后,發現頁面也是刷新了一下(可能的關閉又再打開)。
最后在http://stackoverflow.com/questions/19761241/window-close-and-self-close-do-not-close-the-window-in-chrome看到討論,大概意思是Chrome的新版本加強了安全性和諧了hack雲雲。
然后有人建議使用Chrome的API。
查閱了文檔后,嘗試直接在Content Scripts調用chrome.tabs.remove(id)
來移除,結果報錯說找不到該函數。
繼續查閱文檔后發現Content Scripts是沒有權限調用這個的,但是可以通過sendMessage來發送消息給background.js(插件后台)。
於是采用以下方法:
// Content Scripts中 | |
$("#quit_button").click(function() { | |
chrome.extension.sendMessage({greeting: "close_tab"}); | |
}); | |
// background.js中 | |
chrome.extension.onMessage.addListener(function(request, sender, sendResponse) { | |
console.log("Request comes from content script " + sender.tab.id); | |
if (request.greeting === "close_tab"){ | |
chrome.tabs.remove(sender.tab.id); | |
} | |
}); |
先在background.js中注冊消息處理函數,當點擊按鈕時,Content Scripts向插件后台發送消息,該消息觸發其調用chrome.tabs.remove(id)
來關閉該頁面。
這樣就間接實現了預期目標。