문제

I'm writing a Chrome extension, and want to write one JS file, that provides several expected functions that aren't present in another, then load that other file. I'm after behavior similar to require in Perl, #include in C, or execfile in Python when passing the current modules locals and globals, as though the referenced file was inserted directly into the current script.

Most existing solutions I can find out there refer to embeddeding these "includes" inside script tags, but I'm not sure this applies (and if it does, an explanation of where exactly my extension is injecting all these script tags in the current page).

Update0

Note that I'm writing a content script. At least on the "user" side, I don't provide the original HTML document.

도움이 되었습니까?

해결책

Well the best solution was Chrome-specific. The javascript files are listed in the order they are loaded in the extension's manifest.json, here's an extract of the relevant field:

{
  "content_scripts": [
    {
      "js" : ["contentscript.js", "254195.user.js"]
    }
  ]
}

The javascript files are effectively concatenated in the order given and then executed.

다른 팁

function load_script (url, cache) 
{ 

    var httpRequest = new ActiveXObject("Msxml2.XMLHTTP"); 
    httpRequest.open('GET', url, false); 

    if(!cache)
    {
        httpRequest.setRequestHeader("If-Modified-Since", "Sat, 1 Jan 2000 00:00:00 GMT");
    }

    httpRequest.send(null);
    eval(httpRequest.responseText); 

    var s = httpRequest.responseText.split(/\n/); 
    var r = /^function\s*([a-z_]+)/i; 

    for (var i = 0; i < s.length; i++) 
    { 
        var m = r.exec(s[i]); 
        if (m != null) 
        {
            window[m[1]] = eval(m[1]); 
        }
    }
}

load_script("/script.js",true); 

We use this at our organization to do this. Seems to work well enough.

Did you try :

<script language="javascript" src="otherfile.js">

or (I'm not sure which... but I recall one of them working)

document.write('<script type="text/javascript" src="otherfile.js"></script>');
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top