如何从常规网站调用Chrome扩展程序中定义的功能? [英] How can I call functions defined in a Chrome Extension from regular websites?
问题描述
我想创建一个网站,该网站不属于chrome插件,而只是使用该插件公开给它的一些API.这可能吗,如果可以,我该怎么做?我用谷歌搜索了这个问题,却找不到任何东西.
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.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
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
window.sayHello = function () {
window.postMessage({ type: "FROM_PAGE", text: "Hello from webpage!" }, "*");
}
console.log('Emotiv extension loaded.');
}
我从控制台调用window.sayHello()
I'm calling window.sayHello() from the console
推荐答案
内容脚本在这种情况下可以为您提供帮助.
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://*/*"
],
在扩展名为html的文件中,您可以通过以下方式执行脚本:
In you extension html file, you can then execute the script by:
chrome.tabs.executeScript(null, {file: "content_script.js"});
这篇关于如何从常规网站调用Chrome扩展程序中定义的功能?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!