Я хочу сделать следующее в этом порядке
1. Пользователь нажимает кнопку (id = 'copyDetails') во всплывающем окне
2. Текст из определенных элементов (включая имяполя), которые находятся на странице пользователей, хранятся в хэше и отправляются в background.js
3. Хэш из шага 2 сохраняется в хранилище chrome
4. Получите значение имени (которое является ключом вхэш из шага 2) и вставьте его в элемент (id = 'firstName') во всплывающем окне
Следующий код выполняет все вышеперечисленные шаги, но в неправильном порядке (в настоящее время он выполняет шаги 1, 4, 2, 3)
In popup.js
let copyDetails = document.getElementById('copyDetails');
// This gets the most recently stored name and inserts it into the firstName element (works fine)
chrome.storage.sync.get(['key'], function(result) {
document.getElementById('firstName').innerHTML = result.key.firstName;
});
copyDetails.onclick = function(element) {
chrome.extension.getBackgroundPage().console.log("Step 1 - User clicks button");
// the executeScript gets the DOM from the users current page, and extracts the relevant information for the different customer details (inc. name)
chrome.tabs.executeScript({
code: '(' + modifyDOM + ')();'
}, (results) => {
const customerDetails = results[0];
chrome.runtime.sendMessage({customerDetails: customerDetails}, function(response) {
chrome.extension.getBackgroundPage().console.log("Step 2 - send message");
});
});
chrome.storage.sync.get(['key'], function(result) {
chrome.extension.getBackgroundPage().console.log("Step 4 - retrieve name from storage and insert it into popup html element");
document.getElementById('firstName').innerHTML = result.key.firstName;
});
};
function modifyDOM() {
const customerDetails = {
firstName: document.getElementById('customer_first_name').innerHTML,
lastName: document.getElementById('customer_last_name').innerHTML,
email: document.getElementById('customer_email_address').innerText.split('Generate Email')[0].slice(0, -1),
postcode: document.getElementById('customer_uk_postcode').innerHTML
}
return customerDetails
}
Вот это background.js file
function (request, sender, sendResponse) {
chrome.storage.sync.set({key: request.customerDetails}, function() {
chrome.extension.getBackgroundPage().console.log("Step 3 - save details in a hash in storage");
});
});
Я думаю, что мне нужно использовать обратный вызов на executeScript, нопосле нескольких часов игры с ним я не могу заставить его работать.
Определение готово = Я нажимаю кнопку (id = 'copyDetails') и в фоновой консоли я вижу напечатанные шаги 1, 2, 3, 4 в этом порядке.
В случае необходимости popup.html
<!DOCTYPE html>
<html>
<head>
<style>
button {
height: auto;
width: auto;
outline: none;
}
</style>
</head>
<body>
<button id="copyDetails">Copy Details</button>
<div class='details-button'>First Name: <button id="firstName">N/A</button></div>
<script src="popup.js"></script>
</body>
</html>
И мой manifest.json
{
"name": "Copy customer details",
"version": "1.0",
"description": "Copy customer details from an rfq with the click of a button!",
"permissions": ["contextMenus", "activeTab", "declarativeContent", "storage"],
"background": {
"scripts": ["background.js"],
"persistent": false
},
"page_action": {
"default_popup": "popup.html"
},
"manifest_version": 2
}