简体   繁体   中英

How can I get the content of an externally loaded script tag?

I want to have a bookmarklet retrieve data from an external XML file. I thought that I could download it as a script tag (kind of like described here ) and then traverse the innerHTML of the script tag using normal DOM methods. but when I get the script

fonts = document.createElement("script");
fonts.src = "http://www.myExternal/resource/fonts.xml";
fonts.id = "fontXML";
console.log(fonts.innerHTML) //"" (nothing)

I don't get any innerHTML. Is there anyway I can use this strategy (or anything else) to do what I'm trying to accomplish?

Browsers do not allow script content to be browsed like that. So basically you are facing the standard CORS problem.

  1. If the external resource can answer with JSONP, then use it in your script tag.
  2. If there is proper Allow-Origin header set on the resource, just use AJAX.
  3. If it can neither and you have no access to the resource's code to fix it, then the only option I can imagine is to create your own proxy and either set CORS headers or provide JSONP API

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