0

We are using magento 2.4.7-p3 I have a js script inserted in

admin > content > Configuration > MyStoreView > Html Head > Scripts and Style Sheets

script is from external adress and it runs in every page before head closing tag.

But we don't want this script to run when bots like Google or Bing crawling the site.

Is that possible please and how?

1 Answer 1

2

To load a third-party JavaScript file only if the visitor is not a bot, you can use the following approach -

// List of bot user-agent substrings
const botUserAgents = [
    'Googlebot',
    'Bingbot',
    'Slurp',    // Yahoo
    'DuckDuckBot',
    'Baiduspider',
    'YandexBot',
    'Sogou',
    'Exabot',
    'facebot',  // Facebook
    'ia_archiver'
];

// Function to check if the user-agent matches a bot
function isBot() {
    const userAgent = navigator.userAgent;
    return botUserAgents.some(bot => userAgent.includes(bot));
}

// Load third-party script if not a bot
if (!isBot()) {
    const dyscript = document.createElement('script');
    dyscript.src = 'https://example.com/thirdparty.js'; 
    dyscript.async = true; 
    document.head.appendChild(dyscript);

    console.log('Third-party script added because this is not a bot.');
} else {
    console.log('Third-party script not added because this is a bot.');
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.