Blog

Magento2 – Add custom javascript to ‘My Account’ page or after customer successfully login

In this article, we are going to learn how to add custom javascript/script after customer successfully logs in.

There are two methods to do this.

Method 1 : Through custom theme

Step 1: Create layout file in custom theme

In your custom theme app/code/design/frontend/{Vendor}/{theme}/Magento_Customer/layout/, create layout file customer_account_index.xml

with the content:

<?xml version="1.0"?>

<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
<head>

<script src="Magento_Customer::your_custom.js"/>

</head>

</page>

Step 2: Add js file in the current theme
Put your js file in your current theme at location:

app/code/design/frontend/{Vendor}/{theme}/Magento_Customer/web/js/your_custom.js

Step 3: Deploy changes on the server

  1. Remove folders and file present in the pub/static except .htaccess and also remove folders inside of var/view_preprocessed.
  2. run the following command:

php bin/magento se:s:d -f && php bin/magento c:f

Method 2: Through Custom Module

In this method we are going t perform 3 steps to achieve this.

Step 1: Create new layout file in custom module

In app/code/Vendor/Module_name/view/frontend/layout/customer_account_index.xml.

<?xml version="1.0"?>

<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">

<head>

<script src="namespace_modulename::your_custom.js"/>

</head>

</page>

Step 2: Add js file

Then create new your_custom.js in

app/code/Vendor/Module_name/view/frontend/web/js/{your_custom.js}

Step 3: Clear Cache

Run the following command:- php bin/magento c:f

In this way, you can add script once the customer successfuly logs in.

 

 

One thought on “Magento2 – Add custom javascript to ‘My Account’ page or after customer successfully login

Leave a Reply

Your email address will not be published. Required fields are marked *