0

I have some browser sniffer code using the function detect.js. It works fine when not added to my project. Still, when I try to compile the JavaScript and add it to app.js, I get an error in the console at the first line below, refreshing the browser and detecting the browser version.

Uncaught ReferenceError: forEach is not defined.

// Each Utility var each = forEach = function (obj, iterator, context) { if (obj == null) return; if (nativeForEach && obj.forEach === nativeForEach) { obj.forEach(iterator, context); } else if (obj.length === +obj.length) { for (var i = 0, l = obj.length; i < l; i++) { iterator.call(context, obj[i], i, obj); } } else { for (var key in obj) { if (_.has(obj, key)) { iterator.call(context, obj[key], key, obj); } } } }; 

It seems like compiling the JavaScript is doing something to it. Any suggestions?

5
  • 1
    Detect.js has been last updated in 2015. You should not use it in 2021. Commented Jun 2, 2021 at 11:48
  • 1
    What do you need the browser sniffing for here? We might be able to recommend replacements. Commented Jun 2, 2021 at 11:49
  • npm probably scopes the variables. Take a look at the resulting file. Try window.forEach = function() { ... instead. Commented Jun 2, 2021 at 12:10
  • 1
    Good point AKX - I'm looking at detect-browser npmjs.com/package/detect-browser as an option Commented Jun 2, 2021 at 13:23
  • Get the similar issue with detect-browser (index):300 Uncaught ReferenceError: require is not defined Commented Jun 2, 2021 at 15:36

1 Answer 1

0

If I use the detect-browser package.

npm i detect-browser 

Then add the following to my app.js...

const { detect } = require('detect-browser'); const browser = detect(); try { // handle the case where we don't detect the browser if (browser) { console.log(browser.name); console.log(browser.version); console.log(browser.os); } else { console.log('no browser'); } } catch (e) { console.log(e); } 

And issue an npm run prod...

When I pull up the page, I get the following in my console (no errors).

enter image description here

Sign up to request clarification or add additional context in comments.

1 Comment

I'm sure it does, but the issue must be in a conflict with other js or the webpack compression of the javascript in my laravel-mix setup.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.