所以我通过将内容脚本注入(inject)正文来创建此 chrome 扩展:
这是我的 JavaScript:
测试.js:
$(document).ready(function(){
Url = chrome.extension.getURL('etc.html');
link = '<iframe src="' + Url + '" id="frame" scrolling="no" frameborder="0px"></iframe>';
$('body').prepend(link);
alert($('.test').html());
});
这是etc.html的内容,应该转到iframe
etc.html:
<div class="test">An html</div>
这是我的manifest.json
manifest.json:
{
"content_scripts": [ {
"all_frames": true,
"js": [ "js/jquery.js", "js/test.js" ],
"matches": [ "http://*/*", "https://*/*" ],
"run_at": "document_end"
} ],
"description": "Testing",
"name": "test",
"permissions": [ "tabs", "http://*/*", "https://*/*", "notifications", "management", "unlimitedStorage", "bookmarks", "contextMenus", "cookies", "geolocation", "history", "idle" ],
"version": "2.0.0.53"
}
iframe成功插入body,iframe内容出现,通过chrome检查器看到了...
但是当js运行alert($('.test').html());
行时,它返回null而不是返回html....我到底该怎么做开发此类扩展时访问 iframe 内的内容
我也尝试过 $('#frame').contents().find('.test').html();
无济于事
最佳答案
我很确定你做不到。 现在我在网上找不到任何支持这一点的内容,但我记得遇到过这个问题。我认为这样做的原因是其他脚本和扩展不会干扰您的 etc.html。
你可以做的是让etc.html中的javascript访问并修改它的DOM。如果您需要它与注入(inject) iframe 的内容脚本进行通信,您可以通过后台页面传递消息来实现:http://code.google.com/chrome/extensions/messaging.html
例如,您可以通过简单的一次性请求来完成此操作:
etc.html
chrome.extension.sendRequest(msg)
背景.html
chrome.extension.onRequest.addListener(function(request, sender, sendResponse) {
chrome.tabs.sendRequest(sender.tab.id, request);
});
内容脚本.js
chrome.extension.onRequest.addListener(function(req, sender, sendResponse) {
//do stuff
}
您可以对 postMessage 和 onMessage 执行类似的操作。 如果您需要更多帮助,请告诉我。我在我的扩展中广泛使用了这种技术。
关于javascript - 无法使用 jquery 访问通过 google chrome 内容脚本注入(inject)的 iframe 内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7509688/