问题
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