Skip to content Skip to sidebar Skip to footer

How To Get All Frames To Access One Single Global Variable

I am developing a Chrome extension and need my content script to access all frames of the web page in order to detect some specific fields. Once detected I would attempt to store t

Solution 1:

It'd be more secure and reliable to organize the communication via extension messaging to the background script. Instances of content script run in the main page and all iframes, the main one waits for the data, the others in frames send the data through the background page relay.

The content script:

if (window === top) {
  // main pageconstdata = {};
  chrome.runtime.onMessage.addListener(msg => {
    Object.assign(data, msg.data);
    if (data.email && data.username) {
      console.log('Got both values', data);
    }
  });
} else {
  // inside a frameconstdata = {};
  for (const id of ['username', 'email']) {
    const el = document.getElementById(id);
    if (el) data[id] = el.value; 
  }
  if (Object.keys(data).length)
    chrome.runtime.sendMessage({data});
}

The background script:

chrome.runtime.onMessage.addListener((msg, sender) => {
  // message from a frame?if (msg.data && sender.frameId) {
    // relay it to the main page (frameId: 0)
    chrome.tabs.sendMessage(sender.tab.id, msg, {frameId: 0});
  }
});

Post a Comment for "How To Get All Frames To Access One Single Global Variable"