2010-07-23 133 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调用。