Currently, I have a simple Google Chrome Extension that includes a button. By using AJAX, I am fetching a script from a server in my browser's console. Essentially, clicking on the extension reveals a button which, when clicked, fetches the script from the server and displays it in the console using console.log.
My objective is to execute this script on my current page.
Therefore, my question is - how can I make this script run on the page that I have loaded in my browser's console?
Below is the basic HTML code for the button:
<h4>Click here</h4>
<button class="button button5" id="bt1" >
<img src="a.png" alt="Click Me" style="height:42px;border:0;">
</button>
This is the basic JavaScript code responsible for fetching the script from the server:
var buttonClick = document.getElementById('bt1');
buttonClick.addEventListener('click', loadDoc('https://abcd/xyz/pqr/Script1', myFunction));
function loadDoc(url, cFunction) {
var xhttp;
xhttp=new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var data = this.responseText;
cFunction(this);
chrome.tabs.getSelected(null,function(tab) {
chrome.tabs.executeScript({code: `console.log(${JSON.stringify(data)})`});
chrome.tabs.getCurrent('data');
//console.log(taburl);
});
}
};
xhttp.open("GET", url, true);
xhttp.send();
}
In essence, the script is now stored in the "data" variable.
Instead of manually copying and pasting the script to run it, my goal is for the script to automatically execute on the page once I click the button in my extension.