DSh*_*ltz 6 javascript google-chrome-extension
我有一个使用 content_script 以声明方式指定的扩展:
清单.json:
"content_scripts": [
{
"matches": ["<all_urls>"],
"js": ["content.js"],
"run_at": "document_end"
}
],
Run Code Online (Sandbox Code Playgroud)
我正在阅读它,而不是指定 activeTab 权限,它不会在安装过程中发出有关权限的警报:
https://developer.chrome.com/extensions/activeTab
我的问题是:你如何切换到使用
"permissions":["activeTab"]
Run Code Online (Sandbox Code Playgroud)
从使用 content_scripts ?
这是我调用 content_script 的 popup.js 代码:
chrome.tabs.query({ active: true, currentWindow: true }, function (tabs) {
chrome.tabs.sendMessage(tabs[0].id, { action: "checkForCode" }, function (response) {
if (!!response) { showResults(response.results); }
});
});
Run Code Online (Sandbox Code Playgroud)
和 content_script 的事件处理程序:
chrome.runtime.onMessage.addListener(
function (request, sender, sendResponse) {
if (request.action == "checkForCode") {
getCode(request, sender, sendResponse);//method sends callback.
return true;
}
});
Run Code Online (Sandbox Code Playgroud)
这段代码工作得很好,但我想知道如何将它与 activeTab 权限一起使用。我应该通过 chrome.tags.executeScript() 添加 content.js,然后以同样的方式引用它吗?
在你的manifest.json中你需要设置
"permissions": ["activeTab", "tabs"],
Run Code Online (Sandbox Code Playgroud)
和
"background": {
"scripts": ["content.js"],
"persistent": false
},
Run Code Online (Sandbox Code Playgroud)
以您的 content.js 为例:
// metaCode will be injected and executed in the current tab
// the returned results you can use in callbackFunction
var metaCode = 'var descr = document.querySelector("meta[name=\'description\']");'
+ 'var keyw = document.querySelector("meta[name=\'keywords\']");'
+ 'if (descr) var descr = descr.getAttribute("content");'
+ 'if (keyw) var keyw = keyw.getAttribute("content");'
+ '({'
+ ' description: descr || "",'
+ ' keywords: keyw || "",'
+ '})';
chrome.tabs.executeScript(
tab.id,
{code: metaCode}, // get meta key words
callbackFunktion
);
function callbackFunktion(results) {
var result = results[0];
var description = result.description;
var keywords = result.keywords;
// and so on ... whatever you want
// to do with results from the
// injected script from 'metaCode'
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2090 次 |
| 最近记录: |