我嘗試了許多方法(所有文檔化的過程),通過檢查onUpdated.addListener上的URL將腳本注入特定頁面。最後下面的代碼與'執行'似乎工作,但不完美。我可以獲取警報,但無法通過getElementById/getElementsByName找到頁面的文檔元素。必須在web_accessible_resources清單中列出資源,以便通過擴展之外的頁面加載
當我檢查頁面時,腳本被注入。但在錯誤控制檯中,我得到:
拒絕加載chrome-extension://jfeiadiicafjpmaefageabnpamkapdhe/js/Leoscript.js。必須在web_accessible_resources清單鍵中列出資源,才能通過擴展名外的頁面加載資源。
manifest.json的:
{
"name": "Leo Extension for Job Boards",
"version": "1.6",
"manifest_version": 2,
"content_security_policy": "script-src 'self'; object-src 'self'",
"description": "Leo Extension",
"background": {
"scripts": ["js/Leojshelper.js"],
"persistent": true
},
"content_scripts": [
{
"matches": ["<all_urls>"],
"js": ["js/eventPage.js"],
"run_at" : "document_start"
}
],
"icons":{"48":"images/bob48.png", "128":"images/bob128.png"}, //Define any icon sizes and the files that you want to use with them. 48/128 etc.
"browser_action": {
"default_icon": "images/bob.png", // What icon do you want to display on the chrome toolbar
"default_popup": "LeoExtwatch.html" // The page to popup when button clicked.
},
"permissions": [
"tabs", "<all_urls>" // "http://*/*","https://*/*" // Cross Site Access Requests
],
"web_accessible_resources": ["js/LeoScript.js"]
}
我也給 'web_accessible_resources' 允許腳本,但仍然沒有成功。後臺腳本中的代碼:
chrome.tabs.onUpdated.addListener(function (tabId, changeInfo, tab) {
if (changeInfo.status == 'complete') {
if (tab.url.indexOf("in.yahoo") !== -1) {
chrome.tabs.update(tabId, { url: "https://login.yahoo.com/config/mail?.intl=us" });
chrome.tabs.executeScript(tabId, {
code: "document.body.appendChild(document.createElement('script')).src='" +
chrome.extension.getURL("js/LeoScript.js") + "';"
}, null);
LeoScript.js中的代碼,將被注入特定的頁面。
$(document).ready(function() {
alert('injected');
document.getElementById('username').value='aaaaaaa';
});
內容腳本:我用來注入腳本的eventPage.js。
var script = document.createElement('script');
script.src = chrome.extension.getURL("js/Leoscript.js");
(document.body || document.head || document.documentElement).appendChild(script);
請指點我上面的代碼,將解決權限問題的任何變化。提前致謝。
@方覺:謝謝你的迴應,現在累了,但同樣的結果'拒絕加載LeoScirpt:資源必須列在web_accessible_resources –
我試過了再次,事情似乎更奇怪。當chrome.tabs.executeScript(tabId,{file:...})失敗時(即使代碼完全相同),chrome.tabs.executeScript(tabId,{code:...})成功。 –
再次更新。請看一下。 @VineelGogineni –