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

一笑奈何 提交于 2021-02-07 14:15:58

问题


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:


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


来源:https://stackoverflow.com/questions/18897550/how-can-i-call-functions-defined-in-a-chrome-extension-from-regular-websites

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!