How to Retrieve Odoo Menu Structure from a JavaScript Client
In this section, we illustrate how to fetch the menu structure of an Odoo server using JavaScript from the client side.
If you are unfamiliar with how to install an Odoo server api, please refer to the earlier sections.
HTML and JavaScript Implementation
Below is the index3.html
file that contains the necessary code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Dynamic Menu</title>
<style>
body {
font-family: Arial, sans-serif;
margin: 0;
display: flex;
}
#menu-container {
width: 250px;
background-color: #333;
color: white;
padding: 10px;
height: 100vh;
overflow-y: auto;
}
.menu-item {
padding: 8px;
cursor: pointer;
border-bottom: 1px solid #555;
position: relative;
}
.menu-item:hover {
background-color: #444;
}
.submenu {
padding-left: 20px;
border-left: 2px solid rgba(255, 255, 255, 0.2);
margin-left: 10px;
display: block; /* Always expanded */
}
</style>
</head>
<body>
<div id="menu-container"></div>
<script>
var odoo_url_api = "http://192.168.5.33/api";
var token = null;
async function login_odoo() {
try {
let response = await fetch(`${odoo_url_api}/login`, {
method: 'POST',
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
"username": "admin",
"password": "admin",
"dbname": "hieu_hr"
}),
});
let data = await response.json();
if (data.error?.code) throw data;
return data.data;
} catch (error) {
console.error("Login failed", error);
}
}
async function odoo_get(endpoint) {
try {
let response = await fetch(`${odoo_url_api}${endpoint}`, {
method: "GET",
headers: {
"Authorization": token,
"Content-Type": "application/json"
}
});
let data = await response.json();
if (data.error?.code) throw data;
return data;
} catch (error) {
console.error("API request failed", error);
}
}
function createMenu(menuList, parentElement) {
menuList.forEach(menu => {
let menuItem = document.createElement("div");
menuItem.className = "menu-item";
menuItem.textContent = menu.text;
parentElement.appendChild(menuItem);
if (menu.children.length > 0) {
let subMenu = document.createElement("div");
subMenu.className = "submenu";
parentElement.appendChild(subMenu);
createMenu(menu.children, subMenu);
}
});
}
document.addEventListener('DOMContentLoaded', async function () {
let auth = await login_odoo();
token = auth?.access_token;
let res = await odoo_get("/list-menus");
let menuData = res.data;
if (menuData) {
let menuContainer = document.getElementById("menu-container");
createMenu(menuData, menuContainer);
}
});
</script>
</body>
</html>
Conclusion
Congratulations! You have successfully retrieved and displayed the Odoo menu structure. Now, you can start thinking about exciting ways to interact with it and enhance your application!
Demo
odoo; menu; rest api;
Like
Reply