1

On thirdpartydomain.com I want to embed a simple <script> tag that pulls in a script from mydomain.com/myscript.js, which simply creates a little <div> and pulls partial page content from mydomain.com/mypage.htm.

Here's the script, adapted from: How to embed Javascript widget that depends on jQuery into an unknown environment

var myEmbedId = '12345';
var myEmbedContainerId = 'myEmbedContainer_' + myEmbedId;
document.write('<div id="' + myEmbedContainerId + '">IF ALL GOES WELL, THIS TEXT WILL BE REPLACED WITH MYPAGE.HTM CONTENTS');
document.write('</div>');

    (function (window, document, version, callback) {
        var j, d;
        var loaded = false;
        if (!(j = window.jQuery) || version > j.fn.jquery || callback(j, loaded)) {
            var script = document.createElement("script");
            script.type = "text/javascript";
            script.src = "http://mydomain.com/jquery-1.4.1.min.js";
            script.onload = script.onreadystatechange = function () {
                if (!loaded && (!(d = this.readyState) || d == "loaded" || d == "complete")) {
                    callback((j = window.jQuery).noConflict(1), loaded = true);
                    j(script).remove();
                }
            };
            document.documentElement.childNodes[0].appendChild(script)
        }
    })(window, document, "1.3", function ($, jquery_loaded) {
        $(document).ready(function () {
            alert('jquery loaded!');

            var myRefreshUrl = 'http://mydomain.com/mypage.htm';
            alert('refreshing from ' + myRefreshUrl);

            $.get(myRefreshUrl, function(data){ 
                var returnData = data;
                alert('return data: ' + data);
                $('#' + myEmbedContainerId).html(data); });

            alert('load complete v2');

        });
    });

In IE, I get an Access Denied error from Javascript; in Firefox I just get no data returned.

What's wrong with this?

1 Answer 1

3

You cannot create an AJAX request to a different domain from the one that is hosting the current window context.

To pull off what you're describing, you can do something like:

var script = document.createElement('script');
script.type = 'text/javascript';
script.src = 'http://mydomain.com/dynamic.js?data=somepage.htm';
someContainer.appendChild(script);

Within that dynamic.js, you can wrap the HTML contents in a document.write(). The net effect is the same as inserting the result of the AJAX request at the same point in the DOM.

Sign up to request clarification or add additional context in comments.

1 Comment

Crossdomain is req'd, so document.write() is about to get a workout. Thanks

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.