我正在尝试将 div 从content_script
. 我用下面的代码试了一下:
方法一:
$('body').prepend('<div id="topbar"></div >');
方法二:
$('html:not(:has(parent)) > body:first').prepend('<div id="topbar"></div >');
// Several other similar approaches.
但这里的问题是,它将这个 div 注入到所有发现的主体它(jquery 选择器)中。即如果一个页面包含一个iframe
then,这个div 也会被注入到它,因为ifrmae 包含一个body。
实际上,Approach 2
上面显示的在普通脚本/网络文件中运行良好,但在 chrome 的content_script
. 请帮我解决这个问题。
内容脚本:
var jqueryScript = "Javascript/References/jquery-1.7.min.js";
var topBarPage = "TopBar.html";
// Handle the requests.
chrome.extension.onRequest.addListener(function(request, sender, sendResponse) {
if(request.method == "dockPopup"){
injectPopupToPage();
sendResponse({});
}
else if(request.method == "undockPopup"){
removePopupFromPage();
sendResponse({});
}
else{
sendResponse({});
}
});
// Add the popup/topbar to page
function injectPopupToPage(){
// Create script element
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = chrome.extension.getURL(jqueryScript);
// Append jquery to page header.
$('head').append(script);
// Move the page down. >>>>>>>>>>>> Tried with various ways with no luck!!!!
$('body').css('marginTop','39px');
$('body').css('padding-top','64px');
// Append the top bar to page.
$('body').prepend('<div id="topbar"></div >');
$('#topbar').load(chrome.extension.getURL(topBarPage));
$('#topbar').css({
'background-color': '#FBC619',
'position':'fixed',
'left':'0',
'top':'0',
'width':'100%',
'z-index':'9999'
});
}
// Remove the Popup/Topbar from page.
function removePopupFromPage(){
$('#topbar').remove();
$('body').removeAttr('style');
}
清单.json
{
"name": "Inject",
"manifest_version": 2,
"version": "0.0.0",
"description": "Inject.",
"browser_action": {
"default_popup": "Popup.html"
},
"permissions": [
"tabs",
"chrome://favicon/",
"http://*/*",
"https://*/*"
],
"content_scripts": [
{
"matches": ["http://*/*"],
"js": ["Javascript/References/jquery-1.7.min.js","Javascript/content_script.js"],
"run_at": "document_start",
"all_frames": true
}
],
"web_accessible_resources": ["TopBar.html","Javascript/TopBar.js","Javascript/References/jquery-1.7.min.js"]
}