2010-07-23 89 views
1

有什麼辦法讓遠程JS文件擴展到Chrome擴展?在Chrome擴展中使用遠程JavaScript

我的manifest.json看起來是這樣的:

{ 
    "name": "My Extension", 
    "version": "0.1", 
    "content_scripts": [ 
    { 
     "matches": ["http://*/*"], 
     "js": ["jquery.js", "main.js"], 
     "run_at": "document_end", 
     "all_frames": true 
    } 
    ] 
} 

我想用一個的JavaScript API,它是由在選擇域名的使用限制,所以我不能它插入只是在Chrome加載頁面像這樣:

$('head').append('<script src="http://example.com/myApi.js?key=%key%"></script>'); 

因爲JS API提醒我,我在URL上使用它,我沒有給他們。

我想只使用這個遠程JS的一些功能。 API密鑰可以在本地主機上註冊並使用。

但我沒有任何線索,如何解決這個問題 - 在哪裏把遠程JS文件,以便能夠使用它。

我有一個想法來創建"virtual DOM",但也許這不是一個解決方案,因爲JS API代碼無法執行。

在哪裏可以插入代碼?一些背景頁面?

+0

也許一種解決方案是插入一個iframe(託管在我的域的某處並在API中註冊)頁面並從這裏調用JS函數?這個解決方案可以工作,但它不喜歡我的域/服務器可用性的依賴性。我想在Chrome的某些「沙箱」中執行代碼(在API的視圖中 - 在本地主機上)。 – 2010-07-23 19:38:20

+0

聽起來你只需在瀏覽器中訪問'http://example.com/myApi.js?key =%key%',保存文件,將其稱爲'external.js',並將它放在相同的位置你有'jquery.js'和'main.js'(也可以像這樣:'[「jquery.js」,「main.js」,「external.js」]')將它添加到清單中。 – Adam 2010-07-23 20:37:45

回答

0

試試這個腳本:

if(window.top == window && !document.getElementById('molseek')) 
{ 
    if (document && document.doctype && document.doctype.name && document.doctype.name.toLowerCase() == 'html') { 
     loadToolTip(); 
    } 
    // Weird guest... but if we got an head element, try to validate even if no doctype... 
    else if (document && document.getElementsByTagName('head').length) { 
     loadToolTip(); 
    } 
    // Weird guest #2... but if we got title element, try to validate even if no doctype nor head... 
    else if (document && document.getElementsByTagName('title').length) { 
     loadToolTip(); 
    } 
} 

function loadToolTip(){ 

    (function(s){ 
     if(!window.molseek){ 
      s.src='http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js'; 
      (document.getElementsByTagName("head").item(0)||document.body).appendChild(s) 
     } 
    })(document.createElement('script')); 
    (function(s){ 
     if(!window.apture){ 
      s.src='https://location'; 
      (document.getElementsByTagName("head").item(0)||document.body).appendChild(s) 
     } 
    })(document.createElement('script')); 

} 
3

你嘗試:

var script = document.createElement('script'); 
script.type = 'text/javascript'; 
script.src = 'http://example.com/myApi.js?key=%key%'; 
document.getElementsByTagName('head')[0].appendChild(script); 

我用它在我的谷歌Chrome擴展程序和工作得很好。

+0

我無法得到這個工作,我在background.html頁面中使用它不是一個彈出窗口,這可能是爲什麼? – 2011-04-22 18:00:22

+1

這裏關鍵是什麼? – Pradeep 2014-04-22 06:13:03

0

目前無法找到遠程託管代碼的方式,但仍允許該代碼使用chrome。* javascript調用。