3

是否可以使用間隔進行更新?我曾嘗試過:如何刷新/更新pageMod contentScript?

var timers = require("timers"); 
var pageMod = require("page-mod"); 
var mystyle = ....; 

function func1(){ 
pageMod.PageMod({ 
    include: "*.org", 
    contentScript: mystyle 
}); 
} 
func1(); 

function func2(){ 
    mysyle = http://...... 
} 

timers.setInterval(func2,10000); 

問題是它會開始每隔一段時間註冊一次pageMod幾次。 假設我在mystyle裏面有:alert(「hello world」);所以我會去一些頁面,30秒後,當我刷新單個頁面時,它會在警告框內執行3次「hello world」。我希望它只執行一次,每隔30次更新一次mystle。

回答

3

如果保存頁面-MOD

首先創建您可以直接更改contentScript屬性你的頁面-MOD和保存對象變量,像下面mod。然後在您的間隔中,您可以更改contentScript屬性,如您在func2中看到的那樣。一旦你改變了contentScript,你需要頁面模式以某種方式重新評估頁面,我使用了頁面重新加載,因爲它聽起來像從你的描述中已經發生。

var mod = require("page-mod").PageMod({ 
    include: ["*.org"], 
    contentScript: "alert('the first alert');" 
}); 

function func2(){ 
    // change the contentScript 
    mod.contentScript = "alert('the second alert');"; 
    // cause the page-mod to re-evaluate 
    require("tabs").activeTab.reload(); 
} 

tab = require("tabs").open("http://mozilla.org"); 
require("timers").setInterval(func2, 5 * 1000);