I am creating an extension related to automation. In that extension, the activities we do in DOM/ Web page are captured and finally saved as a json file. A chrome extension Like this. https://sideex.io/
Therefore, My reuirement is this. The Title of the tab where I start the record should be given to the json file when saving. Since several tabs can be captured at onece, the title of the first tab has been obtained and assigned to the global variable in background.js like below.
contentScript-01.js
function getPageInformation() {
const pageTitle = document.getElementsByTagName('title')[0].innerHTML;
const processTitle = pageTitle
.trim()
.toLowerCase()
.replace(/[^a-zA-Z ]/g, '');
const titleToArray = processTitle.split(' ');
const setPageTitle = titleToArray.join('-').concat('-capture.json');
chrome.runtime.sendMessage({
action: 'setPageTitle',
title: setPageTitle
},
function(response) {
if (response.data) {
console.log('response received', response.data);
}
}
);
return setPageTitle;
}
async function saveRecording(contents) {
saveFile(contents);
return Promise.resolve();
}
function saveFile(data) {
const blob = new Blob([data], {
type: 'text/csv'
});
const elem = window.document.createElement('a');
elem.href = window.URL.createObjectURL(blob);
elem.download = 'data.json'; // This should replace with that pageTitle
document.body.appendChild(elem);
elem.click();
document.body.removeChild(elem);
alert('Your File has been saved');
}
background.js
var pageTitle;
chrome.runtime.onMessage.addListener(function(msg, sender, sendResponse) {
if (msg.action == 'setPageTitle') {
pageTitle = msg.title;
console.log(pageTitleRPA);
sendResponse({
data: pageTitle
});
}
}
Below is the second content script that starts and stops the capturing functionaly with small popup.
...
recordButton = document.getElementById('recording_button');
if (recordButton) {
recordButton.addEventListener('click', function() {
chrome.runtime.sendMessage({
action: 'isRecording'
}, function(response) {
if (response) {
chrome.runtime.sendMessage({
action: 'stopRecording'
},
function(response) {
// This response means captured data in json
saveRecording(response).then(() => {
stopRecording(); // change UI button start to stop
});
}
);
} else {
chrome.runtime.sendMessage({
action: 'startRecording'
},
function(response) {
startRecording();
}
);
getPageInformation();
}
});
},
}
How to use the variable in the background to the file name of this json. The background script was used to keep the ttile of the first tab. If you go to a second tab/window through the first tab, the title is saved as the title of the second page. I am using manifest version 3. background script as a service worker. Plase give some help regarding this.