我有一个Chrome扩展名。其代码具有方法getSelectionFromPage()
,该方法捕获网页上所选的文本,并且始终捕获returns true
,如下所示:
function getSelectionFromPage() {
window.selected = true;
chrome.tabs.executeScript({
code: "window.getSelection().toString();"
}, function(selection) {
if (selection[0] != '') {
window.selected = true;
}else{
window.selected = false;
}
});
return true
}
在相同的窗口上下文中,我在控制台上运行了以下命令。
结果可以看到如下:
我也在这里写同样的命令:
getSelectionFromPage() //-> true
window.selected //-> false
(getSelectionFromPage() && window.selected) //-> true
(getSelectionFromPage() && window.selected)
应该是false
。我尝试检查typeof(window.selected)
和typeof(getSelectionFromPage())
,但都返回boolean
。我不明白为什么会这样。
答案 0 :(得分:1)
设置为false的函数是回调。直到当前执行上下文完成后,该命令才会执行。因此,只有在&& window.selection
完成执行之后,才能将其设置为false。
executeScript文档:https://developer.chrome.com/extensions/tabs#method-executeScript
事物的顺序是:
(function () {
window.selected = true; // Runs
chrome.tabs.executeScript({code: "window.getSelection().toString();"}, function(){
window.selected = false;
}); // Calls browser API and set's callback (the anonymous function there) to call later)
// NOTE: the callback function which was set here was NOT executed yet it was only defined.
return true;
})() // true
&& window.selected // this is currently true
// Later, now callback executes
如果您想等待,可以改用Promise
。
function getSelectionFromPage() {
return new Promise(function (resolve) {
chrome.tabs.executeScript(
{code: "window.getSelection().toString();"},
// or just put resolve here instead of defining a function to get value directly
function(v){
resolve(!!v);
}
);
});
}
getSelectionFromPage().then(haveSelection => console.log(haveSelection);