0

I have a browser extension rendering a react webpage in an iframe, and I want to be able to access the current page URL in the page rendered by the iframe.

My current solution is to send a message requesting the URL from background.js, but right now I am not able to send a message or get a response.

I would appreciate if you could help get the messenger working, or if you could let me know of a better way to get the current tab url.

This is the background.js

chrome.runtime.onMessageExternal.addListener((request, sender, sendResponse) => {
  if (request) {
    if (request.message) {
      if (request.message === 'version') {
        sendResponse({ version: '1.1.1.0' })
      } else if (request.message === 'test') {
        // this is where the url would be gotten
        sendResponse("hello world")
      }
    }
  }
  return true
})

This is the file that sends the message

chrome.runtime.sendMessage('<<The local dev id of the extension>>', {message: "test"}, 
  function(response) {
    console.log(response);
  }
);

The listener doesn't log anything to the console when I've included any the file that sends the message receive any response.

Jon Baltz
  • 202
  • 1
  • 7
  • Simply use chrome.tabs.getCurrent in the iframe script. – wOxxOm Jul 02 '21 at 17:29
  • @wOxxOm Sadly chrome.tabs isn't available to the page that is rendered in the iframe. – Jon Baltz Jul 03 '21 at 04:48
  • It will be available if your iframe points to a html file exposed via web_accessible_resources, which is the usual method of using an iframe in an extension, see [this example](https://stackoverflow.com/a/25100953). If you do it differently then you should probably show more of your code. Also make sure you reload the extension on chrome://extensions page after editing the files. – wOxxOm Jul 03 '21 at 04:50
  • Assuming the iframe is not from web_accessible_resources, the alternative is chrome.tabs.get(sender.tab.id, tab => sendResponse(tab.url)) in onMessageExternal. – wOxxOm Jul 03 '21 at 04:54

0 Answers0