Create extension to manipulate DOM from other pages

Asked

Viewed 798 times

6

I wonder if you have any way to manipulate the DOM of another page with my extension.

Ex: I open the extension popup and there is a button, and this button I call a Javascript function:

var n1 = document.getElementById("div1").value;
var n2 = document.getElementById("div2").value;

return n1+n2;

Only when I access the popup DOM, the need is to access the DOM of the open page, and return the sum of the values of the open page to the popup DOM.

Manifest

{
  "name": "Teste",
  "version": "0.0.1",
  "manifest_version": 2,
  "description": "Teste.",
   "browser_action":{
      "default_icon": "icon.png",
      "default_popup": "background.html"
   },
"content_scripts": [
    {
      "matches": ["<all_urls>"],
      "js": ["script.js"]
    }
  ]
  
}

HTML

<html>
<head>
<style>
html,body{width:425px;}
</style>
</head>
<body>
<button onclick="Captura()">Click me</button>
</body>
</html>

Script

alert(document.getElementsByTagName("div").length);

Making some test had the result. Every time I update the google page, my extension shows the amount of div of the same. my doubt is, it is possible to trigger this event only when I click the button in the popup.

1 answer

2

I don’t think you can access directly, however you can perform a function in the scope of the page using executeScript and then collect the result using communication through the Shared DOM.

Example of listening extension per event message:

var port = chrome.runtime.connect();

window.addEventListener("message", function(event) {
  // We only accept messages from ourselves
  if (event.source != window)
    return;

  if (event.data.type && (event.data.type == "FROM_PAGE")) {
    console.log("Content script received: " + event.data.text);
    port.postMessage(event.data.text);
  }
}, false);

Example of injected script sending a message by clicking a page button:

document.getElementById("theButton").addEventListener("click",
    function() {
  window.postMessage({ type: "FROM_PAGE", text: "Hello from the webpage!" }, "*");
}, false);

Browser other questions tagged

You are not signed in. Login or sign up in order to post.