2015-11-06 27 views
0

使用gmail.js庫我編寫了這個函數,該函數從一個事件偵聽器接收一個字符串,並在發送之前將其注入到我的電子郵件正文中。我怎樣才能以某種方式獲得函數來暫停執行,同時等待Event偵聽器從外部腳本獲得答覆?我有一種感覺,它可以通過同步回調來完成,但我不知道那些知道如何去做。我很感謝在這件事上的任何幫助。是否有可能在等待事件偵聽器時停止執行某個函數?

gmail.observe.before('send_message', function(url, body, data, xhr) { 

console.log('In the before send message method'); 

var event = new CustomEvent('Marketing', { 

    detail: { 
     body: xhr.xhrParams.body_params.body, 
     email: gmail.get.user_email() 
    } 
}); 

window.addEventListener('message', function(event) { 
if (event.data.type && (event.data.type == "FROM_PAGE")) { 
    console.log("received a reply"); 
    console.log(event.data.text); 
    newstring = (event.data.candidate); 
    console.log(newstring); 
    console.log(event.data.token); 
    gotNewString = true; 
} 
}); 


window.dispatchEvent(event); 
console.log('sent the message to extension.js'); 
function listen(data){ 
    console.log("123123",JSON.stringify(data)); 
    console.log(data); 
} 

newstring = "Why must you torture me so?"; 

var oldCmml = xhr.xhrParams.url.cmml; 

var body_params = xhr.xhrParams.body_params; 

if (newstring.length > oldCmml) { 
    xhr.xhrParams.url.cmml = newstring.length; 
} else { 
    while (newstring.length < oldCmml) { 
     newstring += ' '; 
    } 
    xhr.xhrParams.url.cmml = newstring.length; 
} 
console.log(newstring); 
body_params.body = newstring; 

console.log("sent"); 

}); 
+0

我想你可能想要的消息事件觸發發送,而不是周圍的其他方法... – dandavis

+0

我希望我能做到這一點,不幸的是,'observe.before'是一個API調用發生在發送時按下按鈕,這是爲了執行這個代碼沒有別的辦法,所以我必須從裏面不知爲何,你不能 –

+0

停止功能。即使你可以用循環來凍結所有東西,這也會阻止消息事件的發生。如果你可以取消從事件之前,您可以稍後再打電話'gmail.observe.trigger'具有相同(或幾乎相同)值作爲取消事件「簡歷」。 – dandavis

回答

0

您不能停止執行回調函數。你將不得不改變調用函數的代碼,等待你的函數完成。這通常是通過提供一個回調函數來進行,你不是要打電話,一旦你完成處理,例如:

gmail.observe.before('send_message', function(url, body, data, xhr, done) { 
    // you can do processing here 

    // and have to call done, to let the caller continue his work 
    done(); 
}); 

聽衆,這顯然是不正常供應,但由於gmail.js是開放的 - 你可以改變它嗎?

相關問題