2 回答

TA貢獻(xiàn)1856條經(jīng)驗 獲得超11個贊
1. 要點
內(nèi)容腳本無法直接訪問全局變量,它們在“隔離的世界”中工作。
然而,內(nèi)容腳本可以獲得 DOM 的“干凈”視圖。這意味著:
內(nèi)容腳本無法看到頁面腳本定義的 JavaScript 變量。
web_accessible_resources
但您仍然可以通過manifest.json
.
2. 一種可能的解決方法
這是實現(xiàn)此目的的一種方法:
manifest.json
:
{
? "manifest_version": 2,
? "name": "Name",
? "version": "0.0.2",
? "description": "Description.",
? "content_scripts": [
? ? {
? ? ? "matches": ["*://*.online-go.com/*"],
? ? ? "js": ["content.js"]
? ? }
? ],
? "web_accessible_resources": ["script.js"]
}
您可以將您可能需要的任何腳本添加到密鑰中,就像上面密鑰web_accessible_resources
中使用的腳本一樣。matches
您還可以使用通配符(例如 )*
同時匹配多個。
您可能仍然需要將其添加到您的:
compilerOptions
內(nèi)部。tsconfig.json
"suppressImplicitAnyIndexErrors": true
script.ts
:
interface Goban {
? bounded_height: number;
}
declare var goban: Goban;
goban = window['global_goban'];
console.log(goban.bounded_height.toString());
content.ts:
const script = document.createElement('script');
script.src = chrome.extension.getURL('script.js');
document.head.append(script);
@types/chrome
例如,您可能還需要通過npm i --save @types/chrome
.
3. 更多資源
window.postMessage
此外,內(nèi)容腳本可以使用和與頁面腳本進(jìn)行通信window.addEventListener
。

TA貢獻(xiàn)1712條經(jīng)驗 獲得超3個贊
如果您在 online-go.com 上的瀏覽器中打開控制臺,您可以輸入goban并看到它是全局可用的,就像這樣。因此,window.goban這將是訪問變量的方式。我會做類似的事情:
interface Goban {
? bounded_height: number;
}
const local_goban: Goban = window.goban;
console.log(local_goban.bounded_height.toString());
要不就
interface Goban {
? bounded_height: number;
}
const goban: Goban = window.goban;
console.log(goban.bounded_height.toString());
在您定義的代碼中g(shù)lobal_goban,但隨后繼續(xù)訪問goban. 確保變量名稱一致。
至于自動從該頁面輸入全局變量,我認(rèn)為這實際上是不可能的。Typescript 不能在瀏覽器中工作,它總是必須編譯為普通的 JS,所以你只需要手動編寫你想要的類型......你可以檢查像 Definely Typed 這樣的東西,但正如你提到的,如果他們沒有沒有發(fā)布任何公共存儲庫及其代碼/包,那么您可能無法找到任何內(nèi)容。
編輯:為了讓打字稿不抱怨窗口變量,您可能需要添加更多類似的內(nèi)容:
type Goban = {
? bounded_height: number;
}
declare global {
? ?var goban: Goban;
}
添加回答
舉報