Reputation: 541
I have a Rails 6 application where I'm interacting with the browser to get some information (getAccount) from a Chrome extension.
On the last line, I do console.log(account)
, which prints the correct value. However, I want to save the account variable to my database. How would I go about exposing that account
variable to Rails so I can send it to the controller and save it?
<%= link_to "Home", root_path %>
<button class="enableEthereumButton">Connect MetaMask</button>
<h2>Account: <span class="showAccount"></span></h2>
<script>
const ethereumButton = document.querySelector('.enableEthereumButton');
const showAccount = document.querySelector('.showAccount');
ethereumButton.addEventListener('click', () => {
getAccount();
});
async function getAccount() {
const accounts = await ethereum.request({ method: 'eth_requestAccounts' });
const account = accounts[0];
showAccount.innerHTML = account;
console.log(account)
}
</script>
Upvotes: 1
Views: 219
Reputation: 541
Based on Kelvin's guidance, I ended up with the following solution:
<script>
const ethereumButton = document.querySelector('.enableEthereumButton');
const showAccount = document.querySelector('.showAccount');
ethereumButton.addEventListener('click', () => {
getAccount();
});
async function getAccount() {
const accounts = await ethereum.request({ method: 'eth_requestAccounts' });
const account = accounts[0];
showAccount.innerHTML = account;
console.log(account)
const response = await fetch('http://localhost:3000/save_eth_address', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
eth_address: account,
})
});
}
</script>
Which sends params to the controller I can easily find and save to the db.
Upvotes: 1
Reputation: 8718
Since Rails runs on the server while this code runs in the browser, you'll need to transmit that data to your backend.
The simplest approach would be making a HTTP POST request to a route on your server, which can directly log the account to your database or do anything else with it.
You could also set up a WebSocket connection between your client and server and exchange information that way, but a simple HTTP POST request is all you really need.
Upvotes: 2