Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I call functions defined in a Chrome Extension from regular websites?

I'd like to make a website that is not part of the chrome plugin but rather just uses some API that the plugin exposes to it. Is this possible and if so, how do I do it? I googled this question and was unable to find anything.

I'm trying to use content scripts but nothing happens. Can someone explain what's wrong here?

manifest.json

{
  "manifest_version": 2,

  "name": "Hello World Extension",
  "description": "This extension prints hello world.",
  "version": "1.0",
  "background": {
    "page": "background.html"
  },
  "browser_action": {
    "default_icon": "img/icon.png",
    "default_popup": "popup.html"
  },
  "content_scripts": [
    {
      "matches": ["http://locahost:8888/*"],
      "js": ["EmotivAPI.js"]
     }
   ]
}

EmotivAPI.js

var port = chrome.runtime.connect();
console.log("Hello?");
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);
        alert("recieved!");
    }
}, false);

js in the webpage

window.sayHello = function () {
        window.postMessage({ type: "FROM_PAGE", text: "Hello from webpage!" }, "*");
    }
    console.log('Emotiv extension loaded.');
}

I'm calling window.sayHello() from the console

like image 351
egucciar Avatar asked Sep 19 '13 14:09

egucciar


1 Answers

Content Scripts can help you in this case.

The content script will be injected into a page:

"content_scripts": [
    {
      "matches": ["http://www.google.com/*"], // try with "http://localhost:*/*" or "http://localhost:*" 
      "css": ["mystyles.css"],
      "js": ["content_script.js"]
    }
  ]

If you want to inject the code only sometimes, use the permissions field instead

/* in manifest.json */
"permissions": [
  "tabs", "http://*/*"
],

In you extension html file, you can then execute the script by:

chrome.tabs.executeScript(null, {file: "content_script.js"});
like image 171
Siddharth Pandey Avatar answered Oct 13 '22 23:10

Siddharth Pandey