1

I have an extension that injects a script into a web page.

The inject script sees all global variables on the page.

But after I click on the button in the extension and send a message to the inject script, all the code in the inject script is re-executed and no longer sees the global variables on the page.

Why this happens and how it can be fixed? Thank you!

inject script:

function parseEssentialDetails() {
  let main = {};

  main.performance = JSON.parse(JSON.stringify(window.testing || localStorage.getItem('testing') || null)) || null;

  if (window.testing) {
    localStorage.setItem('testing', window.testing);
  }
  
  return main;
}

if (!essential) {
  var essential = parseEssentialDetails();
}

const i = 1;

window.postMessage({ type: "FROM_PAGE", essential });

console.log(i)

//any global variable on the page
console.log(window.testing)

if (chrome.runtime) {
  chrome.runtime.onMessage.addListener(message=>{
    if (message.buttonWS) {
      
    }
  });
}

popup script:

let bg = chrome.extension.getBackgroundPage();

let button = document.getElementById("button");

chrome.tabs.query({ active: true, currentWindow: true }, (tabs) => {
  let currentTabId = tabs[0].id;
  let currentPerf = bg.perfWatch[currentTabId].performance;
  if (currentPerf !== 'Best application') {
    alert('Этот сайт не поддерживается')
    document.body.style.display = 'none'
  }
});


function FireInjectionScript() {
  //Want to Pass this variable.
  chrome.tabs.query({active: true, currentWindow: true}, tabs => {
    chrome.tabs.executeScript(tabs[0].id,{file: 'inject-script.js'}, ()=>{
      chrome.tabs.sendMessage(tabs[0].id, {buttonWS: 'ws connect'});
    });
  });
};

button.addEventListener('click', FireInjectionScript);
Jeroen Steenbeeke
  • 3,884
  • 5
  • 17
  • 26

0 Answers0