[英]Closing tabs with a specific meta TAG in firefox-addon using javascript
我有這個插件,它將在其打開的頁面上插入以下“元”標記。最后,我要關閉頁面標題上帶有該TAG的所有標簽。
<meta id="CLOSE_LATER">
我寫了一個簡單的for循環:
var TAG = "CLOSE_LATER";
var tabs = require("sdk/tabs");
for(var i=0; i<tabs.length; i++){
var tab = tabs[i];
console.log("****START****");
console.log("CLOSING TAB : "+i+"of : "+tabs.length);
searchTag(tab, TAG,i)
.then(function success(rValue) {
if (rValue) {
tab.close();
console.log("CLOSED i: "+i);
}
else{
console.log("NOT CLOSED i: "+i);
}
}, function failure(error) {
console.log("Error : searchTag()");
});
console.log("****END****");
}
其中searchTag()將腳本附加到頁面“ seachtag.js”以搜索TAG。
searchTag()返回一個解析為TRUE的promise,如果它在頁面上找到了TAG,否則解析為FALSE。
情況示例:我有3個URL,其中只有URL-2和URL-3的頭部帶有TAG。 因此,只有URL-2和3應該被關閉,而只有URL-3被關閉。
以下是示例日志:
嘗試這個:
var TAG = "CLOSE_LATER";
var tabs = require("sdk/tabs");
var success = function (rValue) {
if (rValue) {
this.close();
//console.log("CLOSED i: "+i);
}
else{
//console.log("NOT CLOSED i: "+i);
}
};
for(var i=0; i<tabs.length; i++){
var tab = tabs[i];
console.log("****START****");
console.log("CLOSING TAB : "+i+"of : "+tabs.length);
searchTag(tab, TAG,i)
.then(success.bind(tab), function failure(error) {
console.log("Error : searchTag()");
});
console.log("****END****");
}
這會將您感興趣的tab
綁定到success
函數中的this
變量,以便每次success
調用都將具有正確的tab
對象。
請注意,我注釋掉了日志記錄,因為您不再擁有對i
訪問權限,但是如果您希望其再次運行,則只需為每個循環迭代將tab
和i
封裝在一個新對象中,然后將其綁定。
我以前沒有在諾言中使用過這個技巧,因此諾言解決方案有可能會打破綁定,但希望不會。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.