Search code examples
javascriptgoogle-chrome-extension

Chrome Extension value won't pass out of if-else statement


I'm writing a Chrome extension that will pass data from a webpage to a file and download it. Ultimately, the file ends up in Obsidian for easy note-taking. The extension works fine most of the time, as long as all the fields exist, so I've started introducing some code for when those elements don't exist.

For example, this is the original code:

const ogImage = document.querySelector('meta[property="og:image"]');
const og_image = ogImage.content;

That works fine until the og:image tag doesn't exist in the page. This is the code I came up with to handle the problem:

const ogImage = document.querySelector('meta[property="og:image"]');
if (ogImage != "") {
  const og_image = ogImage.content;
  console.log(og_image);
} else {
  const og_image = "https://---/vvMtZvn.jpg";
  console.log(og_image);
};

Depending on the page, the console will output the correct value. However, I get errors if I try to use the value outside of this code. The console in the following block replies with: Uncaught ReferenceError: og_image is not defined

const ogImage = document.querySelector('meta[property="og:image"]');
if (ogImage != "") {
  const og_image = ogImage.content;
} else {
  const og_image = "https://i.imgur.com/vvMtZvn.jpg";
};

console.log(og_image);

I've been searching but can't find an answer. Maybe I'm asking the wrong question. Any help would be appreciated.


Solution

  • Please try this.

        let og_image;
        const ogImage = document.querySelector('meta[property="og:image"]');
    
        if (ogImage != null) {
          og_image = ogImage.content;
          console.log(og_image);
        } else {
          og_image = "https://---/vvMtZvn.jpg";
          console.log(og_image);
        };