Avoiding the 'Preventing default inside passive event listener' error in Chrome and OpenLayers 2

Utilizing OpenLayers2 (v2.12) to render a map in the user's browser has been my go-to method. However, since Chrome's recent update, using the mousewheel to zoom in and out of the OpenLayers map also inadvertently scrolls the entire page up and down.

Prior to this Chrome change, zooming in and out within the map functioned smoothly without affecting the page scroll. It was only when I used the mousewheel outside the OpenLayers map that the page would scroll, as intended.

However, now an error message pops up when trying to use the mousewheel within the map:

OpenLayers.min.js:2 [Intervention] Unable to preventDefault inside passive 
event listener due to target being treated as passive. See 
https://www.chromestatus.com/features/6662647093133312

This error likely triggers the unwanted page scrolling behavior.

In response to similar queries related to this error, I attempted adding the

touch-action: none;

CSS style to the OL map container, but it failed to resolve the issue.

The error originates from code within the OpenLayers.js file rather than my own, creating uncertainty about how to rectify it.

The specific piece of code causing the error in the Openlayers.min.js file is:

OpenLayers.Event = {
    stop: function(e, t) {
        t || (e.preventDefault ? e.preventDefault() : e.returnValue = !1),
        e.stopPropagation ? e.stopPropagation() : e.cancelBubble = !0
    },
}

particularly the e.preventDefault() function.

The uncompressed version of the OpenLayers file I'm referencing can be found at: https://cdnjs.cloudflare.com/ajax/libs/openlayers/2.12/OpenLayers.min.js

Here's the HTML code for the OL map:

<div class="container-fluid col-xs-12" style="height: 100%;">
    <div class="row" style="height: 100%;">
        <div class="custom-col-md-10 col-sm-9 col-xs-8" style="height: 100%; overflow-y: hidden; max-height:850px;max-width:1600px;">
            <div class="panel" style="height: 100%; border: solid thin; border-color: darkblue;">
                <div class="panel-body" style="height: 100%; padding: 0px;">
                    <div tabindex="0" id="map" style="height: 100%; width: 100%;">
                    </div>
                </div>
            </div>
       </div>
    </div>
</div>

I am seeking a solution that ensures using the mousewheel within the OpenLayers map solely zooms in and out without triggering page scrolling and eliminates the 'unable to preventDefault' error message.

This issue appears to be exclusive to Chrome, as Firefox and Edge behave correctly.

Appreciate any assistance provided.

Answer №1

There appears to be a recurring issue with certain old examples in OpenLayers 2. Fortunately, running this script can help resolve it.

const eventListenerOptionsSupported = () => {
  let supported = false;

  try {
    const opts = Object.defineProperty({}, 'passive', {
      get() {
        supported = true;
      }
    });

    window.addEventListener('test', null, opts);
    window.removeEventListener('test', null, opts);
  } catch (e) {}

  return supported;
}

const defaultOptions = {
  passive: false,
  capture: false
};
const supportedPassiveTypes = [
  'scroll', 'wheel',
  'touchstart', 'touchmove', 'touchenter', 'touchend', 'touchleave',
  'mouseout', 'mouseleave', 'mouseup', 'mousedown', 'mousemove', 'mouseenter', 'mousewheel', 'mouseover'
];
const getDefaultPassiveOption = (passive, eventName) => {
  if (passive !== undefined) return passive;

  return supportedPassiveTypes.indexOf(eventName) === -1 ? false : defaultOptions.passive;
};

const getWritableOptions = (options) => {
  const passiveDescriptor = Object.getOwnPropertyDescriptor(options, 'passive');

  return passiveDescriptor && passiveDescriptor.writable !== true && passiveDescriptor.set === undefined
    ? Object.assign({}, options)
    : options;
};

const overwriteAddEvent = (superMethod) => {
  EventTarget.prototype.addEventListener = function (type, listener, options) {
    const usesListenerOptions = typeof options === 'object' && options !== null;
    const useCapture          = usesListenerOptions ? options.capture : options;

    options         = usesListenerOptions ? getWritableOptions(options) : {};
    options.passive = getDefaultPassiveOption(options.passive, type);
    options.capture = useCapture === undefined ? defaultOptions.capture : useCapture;

    superMethod.call(this, type, listener, options);
  };

  EventTarget.prototype.addEventListener._original = superMethod;
};

const supportsPassive = eventListenerOptionsSupported();

if (supportsPassive) {
  const addEvent = EventTarget.prototype.addEventListener;
  overwriteAddEvent(addEvent);
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

handlebars and expressjs having trouble displaying the data

Hey there! I'm currently working on an application with express.js and handlebars. I've set up a get method to retrieve employee data when the user enters http://localhost:3000/id/2 in their browser. The id should be 2, and it's supposed to ...

Searching for a specific string within an array using JavaScript: tips and tricks!

I have a variable which looks like this: var d; d = [{'category': 'Hourly Report','from_start_datetime': '2013','format': 'yyyy-mm-dd hh:ii:ss', 'id': 'dateRangeTo'}] When I ...

Determine the corner points of the DOM element following the application of CSS transforms such as rotateX, rotateY, and perspective

To achieve the transformative effect on elements, I utilize rotateX, rotateY, and perspective properties. By using getBoundingClientRect(), I am able to retrieve details such as top, left, bottom, right, width, and height of an element. Is there a method ...

How come I keep running into the "is not a function" issue when trying to use the generateRequest function with Polymer's iron-ajax

Oops, it seems like there was an error: Uncaught TypeError: this.$.ajax.generateRequest is not a function. The issue seems to be in assets-ajax.html at line 23. <dom-module id="assets-pull"> <style> </style> <template> <but ...

Eliminating aliasing from an SVG circular element

I am currently working on creating an animated SVG pie chart. The setup involves two SVG elements, where the first element is given a border-radius of 50%, and the second element is a circle that is filled up to a specific value. This results in one circle ...

The processes of setting and copying operate in distinct ways

I have some questions regarding Set and clone in Three.js. I am attempting to create a scene where a sphere moves along the x-axis and the camera follows the movement using lookAt. I tried replicating an example from a book on learning Three.js, however, w ...

What is the best way to create a subtle transition between two different backgrounds on a website's homepage

I recently made some changes to the Homepage by adding two different backgrounds - one in blue shade and the other as an image. However, I want the blue shade background to be more prominent than the image background. How can I achieve this? <div class ...

Unable to make API call within ReactJs Component due to technical issues

I am brand new to react and I am coming across a few things that I don't quite understand (even after researching). So, I have decided to ask my questions here. Beforehand, I just want to apologize for my poor English and any potentially silly questio ...

Unable to transmit an object containing a property that includes an array of other objects

I am attempting to send an object that has the following structure: var postBody = { id: userID, objectID: [0, 1], objects: [ {id: 0, x: 0.33930041152263374, y: 0.08145246913580247, width: 0.0823045267489712, height: 0. ...

What is the best way to utilize the JavaScript split() method to effectively split pasted text based on new lines?

Could use some assistance with this, please? I am working on contenteditable div elements and I need to enable the ability to copy and paste numbers into them. The numbers may be structured in columns and rows, similar to Excel. Upon pasting, the text sh ...

Maximizing Bootstrap card size in Angular4: A step-by-step guide

How can I make Bootstrap cards resizable on top of other elements when clicked on an icon to make it full screen and overlay on other cards? detail.component.html <div class="card card-outline-info" > <div class="card-header bg-info"><h5 ...

How can I convert the left links in my navigation bar to a CSS drop-down menu to make it more responsive on small screens?

Here is the structure of my HTML (at the top): <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></s ...

Scrape the CNMV.es website using Python to create a payload and execute JavaScript rendering

Upon sending a request to with payload and searching for text 'aaa', I received a javascript response. In order to render the javascript, I am exploring alternatives to using Selenium. Additionally, there is uncertainty regarding the adequacy of ...

Is it possible to update a property value within a redux state by utilizing a value passed in when the action is invoked by the user?

My current challenge involves updating the redux state, which comprises an object with multiple properties. The specific property that needs to be updated depends on user input, making it impractical to have a separate case for each one. For instance, inst ...

Transforming a plain text field into an input field upon clicking a button or icon using Angular/Typescript

I am a beginner with Angular 6 and I'm trying to implement functionality where clicking a button or icon will change a text field into an input field. See the snippet of code and expected output below. Thank you in advance. <div> <mat-for ...

Newly created item not showing up in Bootstrap carousel

Incorporating a bootstrap carousel with ng-repeat into my div has been quite the journey. One challenge I've encountered is adding new items to the current list and smoothly transitioning to that newly added item. For instance, when I am at index 0 a ...

Is there a way to identify the language and style of a text in order to select the appropriate typeface? Alternatively, could someone recommend a different font for me to try?

I am dedicated to offering multilingual support for over 150 different languages all around the world (essentially every language supported by Google Translator). To accomplish this, I rely on Google's Font Family Noto: Noto Sans covers approximately ...

Using jQuery to loop over an array and append to the ajax function

I have a question regarding my jQuery $.ajax() post. I need to include an object (or is it a string?) in the request for each item in an array, but I'm unsure of the best approach to take. I think it might be helpful to separate the items from the dat ...

When transitioning between single-page Angular applications using Protractor, a "JavaScript error: document unloaded while waiting for result" may be encountered

I came across this article discussing the issue of a Javascript error related to a document being unloaded while waiting for a result: JavascriptError: javascript error: document unloaded while waiting for result Although the solution provided seems to wo ...

What is the method to update an element when any of the items in an array is marked as "Confirmed"?

{submissions && submissions.files_set.map((el) => { if (el.confirmed_status === null) { return <DataToConfirm />; } else if (el.confirmed_status === "CONFIRMED") { return <DataSent />; } })} This ...