2013-07-10 67 views
2

當Chrome擴展嘗試通過chrome.executeScript獲取窗口對象中的自定義函數時,它什麼都沒有。擴展無法訪問窗口對象中的自定義函數

例如:

標籤ID:150個

標籤JS:

window.customfunc = function(){return 'yeap';} 

擴展的背景JS:

chrome.tabs.executeScript(150, { code: "console.log(window);" }) 

的manifest.json:

{ 
    "background": { 
     "scripts": [ "background.js" ] 
    }, 
    "content_scripts": [ { 
     "exclude_globs": [ ], 
     "exclude_matches": [ ], 
     "include_globs": [ "*://*/*" ], 
     "js": [ "script.js" ], 
     "matches": [ "http://*/*" ], 
     "run_at": "document_idle" 
    } ], 
    "content_security_policy": "script-src 'self' https://ssl.google-analytics.com; object-src 'self'", 
    "description": "Test", 
    "manifest_version": 2, 
    "name": "Workspace", 
    "permissions": [ "unlimitedStorage", "notifications", "clipboardWrite", "notifications", "clipboardRead", "management", "tabs", "history", "cookies", "idle", "storage", "webRequest", "webRequestBlocking", "contentSettings", "*://*/*" ], 
    "version": "1.0" 
} 

結果:

在控制檯中,window對象不顯示customfunc,所以我們不能chrome.executeScript使用window.customfunc

爲什麼會發生這種情況,我們該如何解決? 謝謝。

回答

3

這是爲了安全。內容腳本(background.js正在執行)與選項卡的腳本(其中定義了customfunc)是隔離的。您還可以獲得額外的好處,即不必擔心名稱空間衝突(這是您搞亂的地方)。

一種方法是創建
myscript.js它說
console.log(window)
,然後使用內容的腳本(或chrome.tabs.executeScript)寫
<script src='chrome.extension.getURL("myscript.js")'></script>
到標籤的DOM。您還需要將
"web_accessible_resources": ["myscript.js"]
添加到您的清單。

但是事情很複雜,一個很好的問題就是爲什麼你需要訪問customfunc。 (你也可以看看https://stackoverflow.com/a/9517879/2336725獲得更長的答案。)

+0

我使用方法2b,它的工作原理!謝謝。 –