tags:

views:

24

answers:

2

I tried the classic ajax approach, but that throws an access denied javascript exception when trying to add a script stored on another domain. Now, I'm sure this is possible since google populates google ads via js only; so does twitter, and the list can continue.

How I thought of it so far:

<div id="divId"></div>
<script type="text/javascript" src="http://mysite.com/script.js"&gt;&lt;/script&gt;

The script in script.js should have changed the innerHTML attribute of the div above. Instead, I get the following message in fireBug: Access to restricted URI denied code: 1012

I googled around a bit but only found workarounds that are useless, like php proxies and such, whereas I want this widget to be copy-pasted into other peoples sites, blogs, forums, etc..

Thanks in advance for any helpful replies. :)

+1  A: 

The behavior that you are seeing is intended and there for security reasons. You wouldn't want a third party script to make any changes to your page as that can be exploited heavily.

Instead, give your users a JavaScript snippet to embed on their page.

<script>
    // do stuff here
</script>

Note that inside this snippet you can create a script tag dynamically, set the src attribute and load the actual JavaScript. This snippet that your users embed on their page has access to the entire DOM, but the script loaded externally does not.

Here's an example of the profile widget that Twitter gives out to embed on web pages:

<!-- external js, can't access or change the DOM -->
<script src="http://widgets.twimg.com/j/2/widget.js"&gt;&lt;/script&gt;
<!-- local js, does that -->
<script>
new TWTR.Widget({
  version: 2,
  ..
  ..
}).render().setUser('hulu').start();
</script>

The first script tag loads the library, while the second one which actually manipulates the page is added as code directly.

Anurag
The problem isn't that I cannot manipulate DOM objects on the page. I can do that.The thing is the browser doesn't let me send an ajax http request to pages outside the current domain were the main page is.That's what "Access to restricted URI denied code: 1012" refers to.And I need the ajax http request to get data from the database.
devland
A: 

I finally found a solution that doesn't involve ajax. I simply use

<div id="objectId"></div>
<script type="text/javascript" src="http://mysite.com/getAndDisplayData.php"&gt;&lt;/script&gt;
<script type="text/javascript">getAndDisplayData();</script>

And in getAndDisplayData.php I generate a JS script that will create my widget inside the div above. The php file also connects to the database and retrieves all required widget data. Apparently this is how google ads works, though I am not sure. It is certain though that they don't use ajax.

devland