简体   繁体   中英

alternative to cross-domain javascripting?

currently i am relying on a proxy script to handle this problem of Single Origin Policy. it is slow, and creates overhead. Not to mention, javascript is not rendered.

is there a working alternative out there?

If you can provide a callback name as a parameter to the service providing the JavaScript code in question, then you can append a script tag to your document, with a src attribute pointing to the service call. Otherwise, you're out of luck.

使用iframe并尝试window.postMessage(message, origin) (来自iframe的parent.postMessage和来自首页的iframeElement.contentWindow.postMessage )适用于所有最新的主流浏览器(Firefox,IE,Safari,Chrome,等)和旧浏览器的更改/轮询window.name

Oh dear, I think the solution you're looking for is with IFRAMEs. However the iframe approach is both a mental and technical undertaking. I suggest you start with this guide:

Cross-Domain Communication with IFrames

The alternative approach is getting data from another server asynchronously using script tags and json:

<script src="http://remotesite.com/path/to/script/blah.js"></script>

You can create a new SCRIPT tag element to pass and load data and append to DOM or insert the markup into an elements innerHTML.

I'm sure you can find some detailed examples and ways to implement but one thing you should keep a track of with the new SCRIPT method is adding so many tot he DOM. This might help and provide a starting point for you:

function require (url, callback) {
    if (!isScriptLoaded(url)) { 
        document.write('<script src="' + url + '" type="text/javascript" charset="utf-8"><\/script>');

        if (callback) {
            callback();
        }
    }
}

function isScriptLoaded(src) {
    var scriptsLoaded =  {};
    var scriptTags    = document.getElementsByTagName("script");

    for (var i = 0, script; script = scriptTags[i]; i++) {
        if (script.src) { 
            scriptsLoaded[script.src] = 1;
        }
    };

    if (scriptsLoaded[src]) {
        return true; 
    }

    return false;
}

(untested, but should work!)

Either way - best of luck.

JSON-P is pretty much ideal for this kind of thing. If you're using jQuery, or similar JavaScript libraries, your job is made even easier:

http://docs.jquery.com/Ajax/jQuery.getJSON#urldatacallback

Of course, it will depend on exactly what you are trying to do that will determine whether to use JSON-P, hidden iframes, postMessage, Flash proxies, or any other exotic solution.

如果您控制两个域并且只关心Firefox 3.5+,则可以使用XMLHttpRequest对象并使用Access Control设置权限。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM