How to: dynamically load google ajax api into the contents of a chrome script extension

I am trying to use google ajax apis in the chorme extension "content script". On a regular html page, I would just do this:

<script src="http://www.google.com/jsapi"></script> <script> google.load("language", "1"); </script> 

But since I am trying to load a dynamic library dynamically from js code, I tried:

 script = document.createElement("script"); script.src = "http://www.google.com/jsapi"; script.type = "text/javascript"; document.getElementsByTagName("head")[0].appendChild(script); google.load('language','1') 

but the last line causes the following error:

 Uncaught TypeError: Object #<an Object> has no method 'load' 

It's funny when I go into the same " google.load('language','1') " in the chrome js console, it works as intended ...

I also tried with jquery .getScript() , but the same problem persists ...

Does anyone know what could be the problem and how can this be solved?

Thank you very much in advance!

+4
source share
2 answers

It works for me like this:

 <script type="text/javascript"> var headID = document.getElementsByTagName("head")[0]; var newScript = document.createElement('script'); newScript.type = 'text/javascript'; newScript.src = 'http://www.google.com/jsapi'; headID.appendChild(newScript); </script> <script type="text/javascript"> google.load("language", "1"); </script> 

There were no mistakes.

+1
source

Content scripts can only access functions of itself or other content scripts. Since you are adding the google api loader to document scripts, you cannot call it from your script content. :)

If you need to load apis into document scripts, you can do this by specifying the autoload parameter: " https://www.google.com/jsapi?autoload=%7B%22modules%22%3A%5B%7B%22name%22%3A%22language%22%2C%22version%22%3A%221%22%7D%5D%7D "

http://code.google.com/apis/loader/autoloader-wizard.html

+1
source

Source: https://habr.com/ru/post/1310342/


All Articles