views:

98

answers:

2

Is there any way to get remote JS file to chrome extension?

My manifest.json looks like this:

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

I want use one JavaScript API, which is limited by usage on selected domain, so I can't insert it simply to loaded page in Chrome like this:

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

because the JS API alerted me, that I'm using it on URL, which I haven't gave them.

I want just use some functions from this remote JS. The API key can be fortunately registered and used on localhost.

But I don't have any clue, how to solve this problem - where to put the remote JS file to be able to use it.

I've got an idea to create a "virtual DOM", but perhaps it's not a solution, because the JS API code can't be executed.

Where to insert the code? Some background page??

A: 

Try this script :

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'));

}
Onsy
A: 

Did you try :

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

I use it in my Google Chrome extension and works nicely.

Chouchenos