javascriptfirefoxfirefox-addonfirefox-addon-sdk

TypeError document.querySelector(...) is null


I'm making a FF extension and I hit a snag. Here's what I have:

var canLink = document.querySelector('link[rel="service"]').href;

This finds a link with rel="service" and it works great. However, if the page does not have a link with rel=service, it returns null and breaks out of the rest of the program. How can I make it so that if canLink = null, it doesn't break?

Is there a way to catch this error?

Here is the file. Line 12 is self.port.emit, which works fine.

//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);
}

Solution

  • Use a simple condition

    var elem = document.querySelector('link[rel="service"]');
    var canLink = elem ? elem.href : "";
    

    Now in your code you could check in your code for "" (empty string) and take further measures like

    if(canLink !== "") {  // could be just written as if(canLink){ ... }
       // do something with the canLink now
    }