skip to Main Content

I am getting the error:
script.js:11 Uncaught TypeError: Cannot read properties of undefined (reading 'includes')

And I don’t understand why. Is the body const incorrect?
How can I fix this?

const checkForText = (url, text) => {
    const page = fetch(url, { mode: 'no-cors' });
    const body = page.text;


    if (body.includes(text)) {
        console.log(`Passed. "${text}" found on ${url}`);
    } else {
        console.error(`Failed. Did not find "${text}" on ${url}!`);
    }
}

checkForText('https://dsbelmex.biz/nosotros/', 'equilibrio');`

I tried a lot of different things, but nothing worked. I’m still learning JavaScript so I’m quite the beginner.

2

Answers


  1. const checkForText = async (url: string, text: string) => {
        const page = await fetch(url, { mode: 'no-cors' });
        const body = await page.text();
    
    
        if (body.includes(text)) {
            console.log(`Passed. "${text}" found on ${url}`);
        } else {
            console.error(`Failed. Did not find "${text}" on ${url}!`);
        }
    }
    
    await checkForText('https://dsbelmex.biz/nosotros/', 'equilibrio');
    
    Login or Signup to reply.
  2. I wouldn’t recommend to try to access external websites directly or interact with the web in real-time to perform actions like searching a webpage for specific content, unless it is in your own server.

    However, I am providing you with a JavaScript function that you can use in your own web development project to search for a specific word on a webpage using JavaScript. You’ll need to run this code within a browser’s developer console or in a JavaScript environment to see the results. Good Luck!

    Example screenshot tested on my browser:
    enter image description here

    async function checkForText(url, word) {
      try {
        const response = await fetch(url, { mode: 'no-cors' });
        if (response.ok) {
          const text = await response.text();
          if (text.includes(word)) {
            return `Passed. "${word}" found on ${url}`;
          } else {
            return `Failed. Did not find "${word}" on ${url}!`
          }
        } else {
          return "Failed to fetch the page.";
        }
      } catch (error) {
        return "An error occurred: " + error.message;
      }
    }
    
    const url = "https://dsbelmex.biz/nosotros/";
    const wordToSearch = "equilibrio";
    
    checkForText(url, wordToSearch)
      .then(result => console.log(result))
      .catch(error => console.error(error));
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search