1

I'm aware of the procedure to add a script with document.createElement('script') but is it just the same for a local file? I've tried using a few function.toString() calls but that's terribly inefficient and would rather store the file I need to add separately, have a loader, and call it a day. Any ideas? This is all for a user script I hope to flawlessly convert into an extension. Thanks.

4

1 回答 1

1

将 设置<script> src为本地文件有效。例如:

addJS_Node (null, 'file:///D:/SAMPLE_DIR/YOUR_CODE.js');

function addJS_Node (text, s_URL, funcToRun) {
    var D                                   = document;
    var scriptNode                          = D.createElement ('script');
    scriptNode.type                         = "text/javascript";
    if (text)       scriptNode.textContent  = text;
    if (s_URL)      scriptNode.src          = s_URL;
    if (funcToRun)  scriptNode.textContent  = '(' + funcToRun.toString() + ')()';

    var targ = D.getElementsByTagName ('head')[0] || D.body || D.documentElement;
    //--- Don't error check here. if DOM not available, should throw error.
    targ.appendChild (scriptNode);
}

重要提示: 您几乎总是必须指定完整路径,因为您希望文件从本地文件系统加载。浏览器会将相对路径解释为相对于当前网页(或<base>标签值)。





回覆:

这都是我希望完美转换为扩展的用户脚本

对于扩展,最好不要将 JS 注入目标页面,而是将其保持在“孤立世界”范围内。

对于扩展程序,或者有时甚至只是专用的 Chrome 用户脚本,可以使用manifest轻松地将文件包含到该范围内。EG(从这里):

{
    "name": "My extension",
    ... 
    "content_scripts": [
        {
            "matches":  ["http://www.google.com/*"],
            "css":      ["mystyles.css"],
            "js":       ["jquery.js", "myscript.js"]
        }
    ],
    ... 
}
于 2012-06-09T19:53:07.790 回答