M
M
MorfeyAsh2017-11-22 14:34:13
JavaScript
MorfeyAsh, 2017-11-22 14:34:13

How to pass variable value from content_scripts in browser extension to page?

There is a task to make a browser extension that changes the content of the page. I am using Firefox.
manifest.json:

{
  "manifest_version": 2,
  "name": "Extension",
  "version": "0.1",
  "icons": {
    "48": "icons/icon-48.png"
  },
  "content_scripts": [
    { 
      "matches": ["*://*/*"],
      "js": ["/content_scripts/jquery.min.js" ]
    }
  ],
  "permissions": [
    "activeTab",
    "tabs",
    "storage"
  ],
  "browser_action": {
    "default_icon": "icons/icon-32.png",
    "theme_icons": [{
        "light": "icons/icon-32-light.png",
        "dark": "icons/icon-32.png",
        "size": 32
    }],
    "default_title": "Extension",
    "default_popup": "popup/extension.html"
  }
}

extension.html
<!DOCTYPE html>

<html>
  <head>
    <meta charset="utf-8">
    <link rel="stylesheet" href="extension.css"/>
  </head>

<body>
  <div id="popup-content">
    <div class="button insert">Insert</div>
  </div>
  <script src="extension.js"></script>
</body>

</html>

extension.js:
function listenForClicks() {
  document.addEventListener("click", (e) => {

    function data_insert(tabs) {
      console.log('==========Extension.js==========');
      browser.tabs.sendMessage(tabs[0].id, {
          command: "insert"
      }).then(response => {
      });
    }

    function onError(error) {
        console.log(`Error: ${error}`);
    }

    if (e.target.classList.contains("insert")) {
      browser.tabs.query({active: true, currentWindow: true})
        .then(data_insert)
        .catch(onError);
    }    
  });
}

function reportExecuteScriptError(error) {
  document.querySelector("#popup-content").classList.add("hidden");
  document.querySelector("#error-content").classList.remove("hidden");
  console.error(`Failed to execute extension content script: ${error.message}`);
}

browser.tabs.executeScript({file: "/content_scripts/background.js"})
.then(listenForClicks)
.catch(reportExecuteScriptError);

background.js:
function insert () {
  var foo = new Date;
  $('body').append('<div>'+foo+'</div>');
}

browser.runtime.onMessage.addListener((message) => {
    if (message.command === "insert") {
      insert();
    }
});

The question is: when you click on "insert", a div with the date is inserted in the extension window:
5a15607d53dc4632470648.png
but the variable itself does not exist in this environment:
5a15608873484774182686.png
Is it possible to get out of such isolation?

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question