[Python] How to execute JavaScript only on a specific view in Odoo 15 without affecting other...

Discussão em 'Python' iniciado por Stack, Abril 22, 2025.

  1. Stack

    Stack Membro Participativo

    I am working on a custom module in Odoo 15 and need to execute JavaScript code on a specific view (the lot verification view). However, the code is currently being executed globally across all views, which is causing errors and poor performance in unrelated views (like Settings).

    The JS works fine on the lot verification view, but it also runs on other views, which causes errors and slows down the application.

    What I'm trying to achieve:

    Execute the JS code only on the lot verification view.

    Prevent the JS from executing in views like Settings, Purchases, etc.

    Maintain the performance of the code as it was originally, with fast execution.

    The lot_enter.js file is being loaded correctly, but the issue is that it runs globally, affecting other views.

    I have tried various ways to limit the code execution to the verification view, but I haven't been able to make it work correctly without it running globally.

    Relevant code:

    odoo.define('verificacion_de_ubicacion.lot_enter', function(require) {
    'use strict';

    const FormRenderer = require('web.FormRenderer');

    FormRenderer.include({
    _renderView: function() {
    this._super.apply(this, arguments);

    // Check if we are on the correct view
    if (this.el && this.el.classList.contains('lot_enter_view')) {
    console.log(' Scanning active on lot verification form');

    setTimeout(() => {
    const input = this.el.querySelector('input[name="escaneado"]');
    const button = this.el.querySelector('button[name="procesar_lote"]');
    if (!input || !button) return;

    // Remove previous event listeners to avoid duplicates
    input.removeEventListener('keydown', handleKeydown);
    input.addEventListener('keydown', handleKeydown);

    function handleKeydown(e) {
    if (e.key === 'Enter') {
    console.log(' Enter key pressed');
    e.preventDefault();
    button.click();
    input.focus();
    input.select();
    }
    }

    // Immediate focus on the input
    input.focus();
    input.select();
    }, 100);
    }
    }
    });
    });


    What I've already tried:

    I tried restricting the JS execution by using conditions in the FormRenderer with classList.contains(), but it still runs globally.

    I tried using an assets_backend.xml file to control the JS loading, but it still runs in all views, including Settings.

    I haven't found a way to ensure the code only runs on the correct view without it affecting other views.

    Question:

    How can I make sure that this JavaScript code runs only on the lot verification view and not on other views like Settings, Purchases, etc.?

    Continue reading...

Compartilhe esta Página