Search code examples
firefoxfirefox-addonfirefox-addon-webextensions

Firefox extension: show iframe by url


I want write a extension for firefox, i wrote a html page with iframe, like as below:

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
</head>

<body>
    <div style="height: 200px; width: 300px;" id="wrapper">
        <iframe src="http://example.com" style="height:200px;width:300px"></iframe>
    </div>
</body>
</html>

It works for me, but i want change iframe url by currnet url, when user click on extension icon, get current url, and change iframe source or delete old iframe and inner new iframe, with new url, like http://example.com/google.com

How can i create this?


Solution

  • when user click on extension icon

    Do you mean the browserAction Icon or PageAction icon?
    There is a difference.
    There is also a difference if the popup is set in manifest.json (automatic) or via an event listener.

    Sample HTML based on your example:

    <!DOCTYPE html>
    <html lang="en">
    
    <head>
      <meta charset="UTF-8">
      <meta name="viewport" content="width=device-width, initial-scale=1.0">
      <meta http-equiv="X-UA-Compatible" content="ie=edge">
    </head>
    
    <body>
      <div style="height: 200px; width: 300px;" id="wrapper">
          <iframe src="" style="height:200px;width:300px"></iframe>
      </div>
      <script src="popup.js"></script>
    </body>
    </html>
    

    Example of popup.js

    // run the function
    setIframe();
    
    async function setIframe() {
    
      // get the active tab
      const tabs = await browser.tabs.query({currentWindow: true, active: true});
    
      // make the URL based on url of the tab i.e. tabs[0].url
      const url = ...... // do whatever
    
      // set iframe to that url 
      document.querySelector('iframe').src = url;
    }