3

I want to put something to work but I am totally confused about googles "isolated worlds". I searched a lot but I cannot find the answer to my needs. Workflow: User clicks on extension icon -> a javascript will search on DOM tree for a div "xpto and get its content -> Use this content to do a google search in a new tab.

manifest.json

{
  "manifest_version": 2,
  "name": "searchongoog",
  "description": "test",
  "version": "1.0",
  "permissions": [ "tabs",
    "https://*/*","http://*/*","activeTab"
  ],    
  "content_scripts": [
    {
      "matches": ["https://*/*","http://*/*"],
      "js": ["background.js"],
      "run_at": "document_end"
    }
  ],
  "browser_action": {
    "default_icon": "icon.png",
    "default_popup": "popup.html"
  }
}

With this I can get the information, but everytime I open a page it automatically gets it done. I dont want that, I want it to do the background.js only when the extension icon is clicked. I tried to invoke the background.js inside popup.html but it doesn't have access to the DOM to extract the information to search.

Any help would be great.

PS: I am a total noob on this, so dont flame me if I am doing totally wrong.

Thanks anyway

4

1 回答 1

6

You could try "programmatic injection" instead of "match patterns injection".

Programmatic injection is useful especially when you don't want to inject code to every page which match the pattern, for example: code should be injected when user click the browser action button.

I wrote a simple example to demonstrate how to implement "programmatic inject":

First, you need to add a background page to register the "browser action" click event listener.

manifest.json

{
  "manifest_version": 2,
  "name": "searchongoog",
  "description": "test",
  "version": "1.0",
  "permissions": [ "tabs",
    "https://*/*","http://*/*","activeTab"
  ],
  "background":{
    "persistent":false,
    "page":"background.html"
  },
  "browser_action": {
    "default_icon": "icon.png"
  }
}

Register the browser action click listener (injector.js is the script that you search the DOM and get content for new tab google searching).

Note: Please make sure that the browser action has no popup. This event will not fire if it has popup.

background.html

<script>
chrome.browserAction.onClicked.addListener(function(tab) {
  chrome.tabs.executeScript(null,{file:"injector.js"});
});
</script>

injector.js

alert("Programmatic injection!");

DEMO snapshot:

enter image description here

Hope this is helpful for you.

于 2013-11-11T06:09:35.383 回答