Problem with load external jsfiles from contentscript.js

5,233 views
Skip to first unread message

chunchulu govindarajulu

unread,
Jan 11, 2011, 8:23:26 AM1/11/11
to Chromium-extensions
Hi,

I am new to this chrome extension plugin development. I am
developing a new new plugin using this chrome extension.

My requirement is load jquery.js file into the content script
when it is not having that js file(For Ex: I am checking for jquery.js
file,fancybox.js file and if it is not there load these files. )

When i implement this logic in content script it is loading the
jquery.js file. After that it is not working in content script . It is
showing $(or) jQuery is undefined. For every time it is loading,but
not executing in the content script.

Here is the code what i implemented.

document.getElementById('someid').onclick = loadJs();


function loadJS() {
if(tyof jQuery == undefined || tyof jQuery != 'function' )
{
var jqscript = document.createElement('script');
jqscript.type = 'text/javascript';
jqscript.async = true;
// Src of the script
jqscript.src = "......url to jquery.js file..............";

// Check whether script is loaded or not
jqscript.onload=function(){
if ((!this.readyState || this.readyState == "loaded" ||
this.readyState == "complete")) {
console.log("Script loaded - ");
// It is showing error here
alert(typeof jQuery);

}
};

// Get the document header
var head = document.getElementsByTagName('head')[0];
// Add script to header - otherwise IE complains
head.appendChild(jqscript);

}


}



Please suggest on this.

Thanks,
C. Govindarajulu

Arne Roomann-Kurrik

unread,
Jan 11, 2011, 6:03:06 PM1/11/11
to chunchulu govindarajulu, Chromium-extensions
This code injects a script tag into the DOM, which means that the code executed will be in relation to the page itself, not the content script.  So while you've probably successfully loaded jquery into the host page, the content script won't have access to the library since content scripts can't directly access javascript methods or objects in the host page.

The correct way to include jquery in a content script is shown here:

Namely, include a local copy of jQuery and then include that file in your content script declaration:

"content_scripts": [{
    "matches": ["http://www.foo.com/*"],
    "js": ["jquery.js", "myscript.js"]
}],

~Arne



--
You received this message because you are subscribed to the Google Groups "Chromium-extensions" group.
To post to this group, send email to chromium-...@chromium.org.
To unsubscribe from this group, send email to chromium-extens...@chromium.org.
For more options, visit this group at http://groups.google.com/a/chromium.org/group/chromium-extensions/?hl=en.


Reply all
Reply to author
Forward
0 new messages