Create extension to manipulate DOM of other pages

6

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

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

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

return n1+n2;

But when I access the popup DOM, the need is to access the open page DOM, and return the sum of the open page values 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);

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

    
asked by anonymous 20.11.2015 / 03:03

1 answer

2

I believe you can not directly access, however you can perform a function in the scope of the page using executeScript and then collect the result using shared DOM >.

Example of extension listening by 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 when you click a button on the page:

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