5
votes

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

1
I don't think that's possible. I think those methods are held securely. With that said, your plugin might be able to inject JS from the plugin into the loaded window, at which point you would be able to access it. It's what, I assume, GreaseMonkey does in some cases.Eli Gassert
you can use content-scripts/page action to match particular or wild card pattern for the url where your app will be hosted.Siddharth Pandey
@Yoda I think this may be what I need. So instead of writing my javascript functions that I want the page to use in the extension pages, I need to put them in the content-scripts page. If the extension wants to send data to the content-script, I just need to pass it via a message. Do content-scripts run in the background?egucciar
@user1274649 check my answer.Siddharth Pandey

1 Answers

2
votes

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"});