[英]How to fix: TypeError: document.querySelector(...) is null
[英]TypeError document.querySelector(...) is null
我正在做一個 FF 擴展,但遇到了障礙。 這是我所擁有的:
var canLink = document.querySelector('link[rel="service"]').href;
這會找到一個帶有 rel="service" 的鏈接,並且效果很好。 但是,如果頁面沒有 rel=service 的鏈接,則返回 null 並跳出程序的 rest。 如果 canLink = null,我怎樣才能使它不會中斷?
有沒有辦法捕捉到這個錯誤?
這是文件。 第 12 行是 self.port.emit,它工作正常。
//Get link if it exists
var elem = document.querySelector('link[rel="service"]').href,
canLink = elem ? elem.href : "";
if (canLink){
self.port.emit("link", canLink);
}
else {
canLink = "";
self.port.emit("link", canLink);
}
使用簡單的條件
var elem = document.querySelector('link[rel="service"]');
var canLink = elem ? elem.href : "";
現在在您的代碼中,您可以檢查代碼中的""
(空字符串)並采取進一步的措施
if(canLink !== "") { // could be just written as if(canLink){ ... }
// do something with the canLink now
}
利用
try{
//code you want to execute
}
catch{
//just console if you want to see error
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.