からページの本文にdivを挿入しようとしていますcontent_script
。私は次のコードでそれを試しました:
アプローチ1:
$('body').prepend('<div id="topbar"></div >');
アプローチ2:
$('html:not(:has(parent)) > body:first').prepend('<div id="topbar"></div >');
// Several other similar approaches.
しかし、ここでの問題は、このdivを検出されたすべての本体のit(jqueryセレクター)に挿入することです。つまり、ページにiframe
thenが含まれている場合、ifrmaeには本体が含まれているため、このdivもページに挿入されます。
実際、Approach 2
上記の例は通常のスクリプト/ Webファイルではうまく機能しますが、chromeでは機能しませんcontent_script
。これを解決するのを手伝ってください。
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"]
}