Javascript 从 chrome 扩展访问当前的 html 页面
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7697001/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
accessing the current html page from chrome extension
提问by DanielB
I'm new to chrome extensions.
I would like to create a simple chrome extension that popup an alert with the title of the current html page.
when I'm performing: alert(document.title)
, I'm not getting it because the document object doesn't belong to the page but to the extension script (is it correct?)
how do i get the right document object?
我是 chrome 扩展的新手。我想创建一个简单的 chrome 扩展,它会弹出一个带有当前 html 页面标题的警报。当我执行: 时alert(document.title)
,我没有得到它,因为文档对象不属于页面而是属于扩展脚本(是否正确?)我如何获得正确的文档对象?
采纳答案by pimvdb
回答by Rob W
Content scripts are the easiest way to go:
内容脚本是最简单的方法:
Expand your manifest file with this code:
使用以下代码展开您的清单文件:
...
"content_scripts": [
{
"matches": ["http://urlhere/*"],
"js": ["contentscript.js"]
}
],
...
Content script (automatically executed on each page as mentioned at matches
at the manifest file):
内容脚本(matches
在清单文件中提到的每个页面上自动执行):
alert(document.title)
The advantage of using content scripts over chrome.extension.*
methods is that your extension doesn't require scary permissions, such as tabs
.
使用内容脚本而不是chrome.extension.*
方法的优势在于您的扩展不需要可怕的权限,例如tabs
.
也可以看看:
回答by Partial Science
For what your doing all you need to do is this
对于你所做的,你需要做的就是这个
chrome.tabs.executeScript({
code: 'alert(document.title)'
})
The chrome.tabs.executeScript api allows you to run JavaScript in the current page instead of in the extension so this works just fine but if you want to use the name of the page later in a more complex extension than I would just do what pimvdb did
chrome.tabs.executeScript api 允许您在当前页面而不是扩展中运行 JavaScript,因此这可以正常工作,但是如果您想稍后在更复杂的扩展中使用页面名称,那么我只会做 pimvdb做过
回答by stu-b-doo
I use this extension to do a similar thing:
我使用这个扩展来做类似的事情:
main.js:
主要.js:
(function(){window.prompt('Page title:', document.title)})()
(function(){window.prompt('Page title:', document.title)})()
manifest.json:
清单.json:
{
"background": {"scripts": ["background.js"]},
"browser_action": {
"default_title": "popup_title"
},
"name": "popup_title",
"description": "Display the page title for copying",
"permissions": [
"tabs",
"http://*/*",
"https://*/*"
],
"version": "1.0",
"manifest_version": 2
}
background.js:
背景.js:
chrome.browserAction.onClicked.addListener(function(tab) {
chrome.tabs.executeScript(tab.id, {file: "main.js"})
});