Rectangle 27 2

Can you eliminate inline script if written in options.html.

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

to your manifest.json and write your injection code for execution at current page in myscript.js

I kind of guessed that from the error code. Also I need to execute this script inside of the current page not the options page. Thanks.

then you have to use content scripts for execution in current page, i have updated my answer on how to'?

I do not want to use content scripts because I need the match url to be dynamic. I need it to execute on any page that has google and maps in the url. Not just the list of urls that I can list by hand.

jQuery use in Google Chrome Extensions - Stack Overflow

jquery google-chrome-extension content-security-policy
Rectangle 27 2

Can you eliminate inline script if written in options.html.

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

to your manifest.json and write your injection code for execution at current page in myscript.js

I kind of guessed that from the error code. Also I need to execute this script inside of the current page not the options page. Thanks.

then you have to use content scripts for execution in current page, i have updated my answer on how to'?

I do not want to use content scripts because I need the match url to be dynamic. I need it to execute on any page that has google and maps in the url. Not just the list of urls that I can list by hand.

jQuery use in Google Chrome Extensions - Stack Overflow

jquery google-chrome-extension content-security-policy
Rectangle 27 44

"background"
manifest.json
jquery.js
background.js
...
"background": { "scripts": ["jquery.js","background.js"] },
...

This should do the job. Remember the js files are loaded in the order they are specified.

in background.js

if (jQuery) {  
    // jQuery loaded
} else {
    // jQuery not loaded
}

this tells you how to get JQuery loaded with your background script, but note the other answers... you can't access the DOM of the active web page. You can access $(document), but that's the background HTML page.

When I used your test in my content_script (not background), I would get an exception saying that jQuery isn't defined. I had to change to if (typeof jQuery !== 'undefined') to actually check if jQuery was defined.

How to use jquery in google chrome extension page action background.js...

jquery google-chrome-extension content-script
Rectangle 27 41

"background"
manifest.json
jquery.js
background.js
...
"background": { "scripts": ["jquery.js","background.js"] },
...

This should do the job. Remember the js files are loaded in the order they are specified.

in background.js

if (jQuery) {  
    // jQuery loaded
} else {
    // jQuery not loaded
}

this tells you how to get JQuery loaded with your background script, but note the other answers... you can't access the DOM of the active web page. You can access $(document), but that's the background HTML page.

When I used your test in my content_script (not background), I would get an exception saying that jQuery isn't defined. I had to change to if (typeof jQuery !== 'undefined') to actually check if jQuery was defined.

How to use jquery in google chrome extension page action background.js...

jquery google-chrome-extension content-script
Rectangle 27 11

If you are fine looking at something beyond a Google Chrome Plugin, look at phantomjs which uses Qt-Webkit in background and runs just like a browser incuding making ajax requests. You can call it a headless browser as it doesn't display the output on a screen and can quitely work in background while you are doing other stuff. If you want, you can export out images, pdf out of the pages it fetches. It provides JS interface to load pages, clicking on buttons etc much like you have in a browser. You can also inject custom JS for example jQuery on any of the pages you want to scrape and use it to access the dom and export out desired data. As its using Webkit its rendering behaviour is exactly like Google Chrome.

Another option would be to use Aptana Jaxer which is based on Mozilla Engine and is very good concept in itself. It can be used as a simple scraping tool as well.

Really got me going there for a while, but none of them seem to be able to integrate into a Google Chrome Extension unfortunately :( They are both stand-alone products that has to be handled in its own environment. Very nice try though.

@SebNilsson Forgot to mention that earlier, have edited the answer. I assumed your need to have the solution as chrome extension is solely based on your need to get a real browser interacting with the site.

Web Scraping in a Google Chrome Extension (JavaScript + Chrome APIs) -...

javascript google-chrome google-chrome-extension xmlhttprequest web-scraping
Rectangle 27 9

Apparently a "background" javascript page can't access the DOM of a webpage in the browser so loading jquery doesn't really make sense in the background script. Instead I have the background script programmatically inject the jQuery library and then the content script into the current webpage. The content script (unlike the background script) can access info on the webpage.

function handleClick(tab) {
    chrome.tabs.executeScript(null, { file: "jquery-1.8.2.min.js" }, function() {
        chrome.tabs.executeScript(null, { file: "content.js" });
    });
}

chrome.pageAction.onClicked.addListener(handleClick);
var text = jQuery('h1').text();
alert('inside content! ' + text);

you can still use JQuery to do Ajax calls etc. No necesarily usless to use JQuery on background.js

How to use jquery in google chrome extension page action background.js...

jquery google-chrome-extension content-script
Rectangle 27 9

Apparently a "background" javascript page can't access the DOM of a webpage in the browser so loading jquery doesn't really make sense in the background script. Instead I have the background script programmatically inject the jQuery library and then the content script into the current webpage. The content script (unlike the background script) can access info on the webpage.

function handleClick(tab) {
    chrome.tabs.executeScript(null, { file: "jquery-1.8.2.min.js" }, function() {
        chrome.tabs.executeScript(null, { file: "content.js" });
    });
}

chrome.pageAction.onClicked.addListener(handleClick);
var text = jQuery('h1').text();
alert('inside content! ' + text);

you can still use JQuery to do Ajax calls etc. No necesarily usless to use JQuery on background.js

How to use jquery in google chrome extension page action background.js...

jquery google-chrome-extension content-script
Rectangle 27 4

Javascript is sandboxed so there will be no conflicts, but CSS isn't, so any styles on parent site will affect your styling and vice versa (aka a nightmare).

javascript - Is it safe to use jQuery and jQuery-UI with Google Chrome...

javascript jquery jquery-ui google-chrome google-chrome-extension
Rectangle 27 3

My understanding is that it's not necessary to use background.js. You can have your code in popup.js instead. Therefore you won't need to include anything in the manifest file either.

I'd suggest to include the jQuery JS and your popup.js in your popup.html:

<script src="/js/jquery-1.8.1.min.js"></script>
<script src="/js/popup.js"></script>

Then in popup.js you should be able to access jQuery, so your eventHandler would look like this:

$(document).ready(function(){
 $('#anyelement').on('click', doSomething);

 function doSomething(){
   alert ('do something');
 };
})

I don't think why you want CDN for jQuery, all the files will be hosted on the user's machine.

good point about not needing CDN. What is popup.html? I don't know what that is. To clarify, the onclick is triggered when the user clicks on the page action's icon.

popup.html is the html content that 'pops up' when you click your extension icon in Chrome.

ok but for my extension, I don't want a popup.

Ok then, try @Archer's solution above, that might be a better one for you.

How to use jquery in google chrome extension page action background.js...

jquery google-chrome-extension content-script
Rectangle 27 3

My understanding is that it's not necessary to use background.js. You can have your code in popup.js instead. Therefore you won't need to include anything in the manifest file either.

I'd suggest to include the jQuery JS and your popup.js in your popup.html:

<script src="/js/jquery-1.8.1.min.js"></script>
<script src="/js/popup.js"></script>

Then in popup.js you should be able to access jQuery, so your eventHandler would look like this:

$(document).ready(function(){
 $('#anyelement').on('click', doSomething);

 function doSomething(){
   alert ('do something');
 };
})

I don't think why you want CDN for jQuery, all the files will be hosted on the user's machine.

good point about not needing CDN. What is popup.html? I don't know what that is. To clarify, the onclick is triggered when the user clicks on the page action's icon.

popup.html is the html content that 'pops up' when you click your extension icon in Chrome.

ok but for my extension, I don't want a popup.

Ok then, try @Archer's solution above, that might be a better one for you.

How to use jquery in google chrome extension page action background.js...

jquery google-chrome-extension content-script
Rectangle 27 186

// ==UserScript==
// @name         jQuery For Chrome (A Cross Browser Example)
// @namespace    jQueryForChromeExample
// @include      *
// @author       Erik Vergobbi Vold & Tyler G. Hicks-Wright
// @description  This userscript is meant to be an example on how to use jQuery in a userscript on Google Chrome.
// ==/UserScript==

// a function that loads jQuery and calls a callback function when jQuery has finished loading
function addJQuery(callback) {
  var script = document.createElement("script");
  script.setAttribute("src", "//ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js");
  script.addEventListener('load', function() {
    var script = document.createElement("script");
    script.textContent = "window.jQ=jQuery.noConflict(true);(" + callback.toString() + ")();";
    document.body.appendChild(script);
  }, false);
  document.body.appendChild(script);
}

// the guts of this userscript
function main() {
  // Note, jQ replaces $ to avoid conflicts.
  alert("There are " + jQ('a').length + " links on this page.");
}

// load jQuery and execute the main function
addJQuery(main);

Instead of the 3 lines inside addEventListener for 'load', wouldn't "callback();" just work?

My page already includes jQuery, but it seems that the above code is still needed to use jQuery in the userscript. However, two jQuery includes can cause a conflict, so the first line of your main() function might need to be jQuery.noConflict();

script.textContent = "(" + callback.toString() + ")();";
script.textContent = "jQuery.noConflict();(" + callback.toString() + ")();";

@hippietrail In main(), you can use $.loadScript(), and then have everything else run when loadScript is finished loading jQueryUI.

-1: With that method, the code in main will execute in the context of the target page, meaning that (among other things) the cross-site request policy of the target page applies - (e.g. I had to reinject GM_xmlhttpRequest before seeing that it did not help me). In the end I simply copy pasted the code of jquery.min.js.

How can I use jQuery in Greasemonkey scripts in Google Chrome? - Stack...

jquery google-chrome greasemonkey require userscripts
Rectangle 27 186

// ==UserScript==
// @name         jQuery For Chrome (A Cross Browser Example)
// @namespace    jQueryForChromeExample
// @include      *
// @author       Erik Vergobbi Vold & Tyler G. Hicks-Wright
// @description  This userscript is meant to be an example on how to use jQuery in a userscript on Google Chrome.
// ==/UserScript==

// a function that loads jQuery and calls a callback function when jQuery has finished loading
function addJQuery(callback) {
  var script = document.createElement("script");
  script.setAttribute("src", "//ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js");
  script.addEventListener('load', function() {
    var script = document.createElement("script");
    script.textContent = "window.jQ=jQuery.noConflict(true);(" + callback.toString() + ")();";
    document.body.appendChild(script);
  }, false);
  document.body.appendChild(script);
}

// the guts of this userscript
function main() {
  // Note, jQ replaces $ to avoid conflicts.
  alert("There are " + jQ('a').length + " links on this page.");
}

// load jQuery and execute the main function
addJQuery(main);

Instead of the 3 lines inside addEventListener for 'load', wouldn't "callback();" just work?

My page already includes jQuery, but it seems that the above code is still needed to use jQuery in the userscript. However, two jQuery includes can cause a conflict, so the first line of your main() function might need to be jQuery.noConflict();

script.textContent = "(" + callback.toString() + ")();";
script.textContent = "jQuery.noConflict();(" + callback.toString() + ")();";

@hippietrail In main(), you can use $.loadScript(), and then have everything else run when loadScript is finished loading jQueryUI.

-1: With that method, the code in main will execute in the context of the target page, meaning that (among other things) the cross-site request policy of the target page applies - (e.g. I had to reinject GM_xmlhttpRequest before seeing that it did not help me). In the end I simply copy pasted the code of jquery.min.js.

How can I use jQuery in Greasemonkey scripts in Google Chrome? - Stack...

jquery google-chrome greasemonkey require userscripts
Rectangle 27 2

Yes there can be conflicts, however you can prevent them. When you are setting up a theme, you need to download it with a namespace(you can find that setting in the right column of the jquery ui custom download page), and then use that namespace in your extension. The only possible issue at that point is if the site that is being viewed uses the same namespace that you choose, so make sure you choose something that won't have that problem.

javascript - Is it safe to use jQuery and jQuery-UI with Google Chrome...

javascript jquery jquery-ui google-chrome google-chrome-extension
Rectangle 27 2

Yes, I know. I can use jQuery in javascript which I included in popup.html, but I want to use jQuery in my content script too, but it doesn't work unfortunately...

You said you see the error when you click on your browser action icon. That would mean the error comes from the popup, not the content script.

@anykey3, Do not post updates to the question as answers! Edit the question instead. Also, the code snippet is obviously not valid syntax. Stop editing or hiding the code. If it's sensitive, make a proper working example with valid syntax and that we can run AS-IS, to see the problem you report.

Ok, thanks. I will have it in view

JQuery is not working in my Google Chrome extension, content script? -...

jquery google-chrome-extension content-script
Rectangle 27 2

Part of the reason this is so confusing is because jQuery API confuses the issue of Ajax calls vs JSONP calls. When using $.ajax with dataType: 'jsonp' this does not do an Ajax call (no XHR communication is used) it instead uses dynamic script injection with a callback. This means that the type: 'POST' will have no meaning (since dynamic script injection only works as a GET would work) and that all of the data will be encoded into the URL of the request as opposed to being send over as a post body. If this is truly intended to "POST" data then JSONP should not be used (since sensitive data will be sent in clear text).

As mentioned in one of the comments, this issue was addressed in this answer with regards to JSONP requests from Chrome content scripts and using XHR from a content script.

With regards to Chrome Extensions, they do force you into a sandbox when using the "conten scripts" in a chrome extension. You can remove the dataType: 'jsonp' form the request in the Chrome Extension content script and this call should work. If that does not work, you might trying making the call directly using the XHRHttpRequest:

var xhr = new XMLHttpRequest();
xhr.setRequestHeader("Content-Type", "application/json; charset=utf-8");
xhr.open("POST", $(this).attr('action'), true);
xhr.onreadystatechange = function() {
    if (xhr.readyState == 4) {
       alert("A");
  }
}
xhr.send($(this).serialize());

With regards to other browsers, I am not sure how each of their specific plugin enviroments handle making cross domain XHR calls (or if they even allow it in the first place). This is something that is NOT allowed from normal browsers (unless using something like easyXDM).

Thanks for the answer, i realised now the problem. I just simply add the url of the target site into to permissions list and now it's working with regular AJAX requests fine.

javascript - JSONP communication in a Google Chrome extension - Stack ...

javascript jquery google-chrome-extension jsonp
Rectangle 27 43

Example Usage

I have written a few functions based on the Erik Vold's script to help run me run functions, code and other scripts in a document. You can use them to load jQuery into the page and then run code under the global window scope.

// ==UserScript==
// @name           Example from http://stackoverflow.com/q/6834930
// @version        1.3
// @namespace      http://stackoverflow.com/q/6834930
// @description    An example, adding a border to a post on Stack Overflow.
// @include        http://stackoverflow.com/questions/2246901/*
// ==/UserScript==

var load,execute,loadAndExecute;load=function(a,b,c){var d;d=document.createElement("script"),d.setAttribute("src",a),b!=null&&d.addEventListener("load",b),c!=null&&d.addEventListener("error",c),document.body.appendChild(d);return d},execute=function(a){var b,c;typeof a=="function"?b="("+a+")();":b=a,c=document.createElement("script"),c.textContent=b,document.body.appendChild(c);return c},loadAndExecute=function(a,b){return load(a,function(){return execute(b)})};

loadAndExecute("//ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js", function() {
    $("#answer-6834930").css("border", ".5em solid black");
});

You can click here to install it, if you trust that I'm not trying to trick you into installing something malicious and that nobody has edited my post to point to something else. Reload the page and you should see a border around my post.

Loads the script at url into the document. Optionally, callbacks may be provided for onLoad and onError.

Inserts a function or string of code into the document and executes it. The functions are converted to source code before being inserted, so they lose their current scope/closures and are run underneath the global window scope.

A shortcut; this loads a script from url, then inserts and executes functionOrCode if successful.

function load(url, onLoad, onError) {
    e = document.createElement("script");
    e.setAttribute("src", url);

    if (onLoad != null) { e.addEventListener("load", onLoad); }
    if (onError != null) { e.addEventListener("error", onError); }

    document.body.appendChild(e);

    return e;
}

function execute(functionOrCode) {
    if (typeof functionOrCode === "function") {
        code = "(" + functionOrCode + ")();";
    } else {
        code = functionOrCode;
    }

    e = document.createElement("script");
    e.textContent = code;

    document.body.appendChild(e);

    return e;
}

function loadAndExecute(url, functionOrCode) {
    load(url, function() { execute(functionOrCode); });
}

extra points for the useless coffee script abstraction

@cyphunk Yeah, it was crucial for me to save those few characters. Actually, I'm feeling pretty dumb for having left this post using it so pointlessly. I'll remove it.

How can I use jQuery in Greasemonkey scripts in Google Chrome? - Stack...

jquery google-chrome greasemonkey require userscripts
Rectangle 27 43

Example Usage

I have written a few functions based on the Erik Vold's script to help run me run functions, code and other scripts in a document. You can use them to load jQuery into the page and then run code under the global window scope.

// ==UserScript==
// @name           Example from http://stackoverflow.com/q/6834930
// @version        1.3
// @namespace      http://stackoverflow.com/q/6834930
// @description    An example, adding a border to a post on Stack Overflow.
// @include        http://stackoverflow.com/questions/2246901/*
// ==/UserScript==

var load,execute,loadAndExecute;load=function(a,b,c){var d;d=document.createElement("script"),d.setAttribute("src",a),b!=null&&d.addEventListener("load",b),c!=null&&d.addEventListener("error",c),document.body.appendChild(d);return d},execute=function(a){var b,c;typeof a=="function"?b="("+a+")();":b=a,c=document.createElement("script"),c.textContent=b,document.body.appendChild(c);return c},loadAndExecute=function(a,b){return load(a,function(){return execute(b)})};

loadAndExecute("//ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js", function() {
    $("#answer-6834930").css("border", ".5em solid black");
});

You can click here to install it, if you trust that I'm not trying to trick you into installing something malicious and that nobody has edited my post to point to something else. Reload the page and you should see a border around my post.

Loads the script at url into the document. Optionally, callbacks may be provided for onLoad and onError.

Inserts a function or string of code into the document and executes it. The functions are converted to source code before being inserted, so they lose their current scope/closures and are run underneath the global window scope.

A shortcut; this loads a script from url, then inserts and executes functionOrCode if successful.

function load(url, onLoad, onError) {
    e = document.createElement("script");
    e.setAttribute("src", url);

    if (onLoad != null) { e.addEventListener("load", onLoad); }
    if (onError != null) { e.addEventListener("error", onError); }

    document.body.appendChild(e);

    return e;
}

function execute(functionOrCode) {
    if (typeof functionOrCode === "function") {
        code = "(" + functionOrCode + ")();";
    } else {
        code = functionOrCode;
    }

    e = document.createElement("script");
    e.textContent = code;

    document.body.appendChild(e);

    return e;
}

function loadAndExecute(url, functionOrCode) {
    load(url, function() { execute(functionOrCode); });
}

extra points for the useless coffee script abstraction

@cyphunk Yeah, it was crucial for me to save those few characters. Actually, I'm feeling pretty dumb for having left this post using it so pointlessly. I'll remove it.

How can I use jQuery in Greasemonkey scripts in Google Chrome? - Stack...

jquery google-chrome greasemonkey require userscripts
Rectangle 27 2

Part of the reason this is so confusing is because jQuery API confuses the issue of Ajax calls vs JSONP calls. When using $.ajax with dataType: 'jsonp' this does not do an Ajax call (no XHR communication is used) it instead uses dynamic script injection with a callback. This means that the type: 'POST' will have no meaning (since dynamic script injection only works as a GET would work) and that all of the data will be encoded into the URL of the request as opposed to being send over as a post body. If this is truly intended to "POST" data then JSONP should not be used (since sensitive data will be sent in clear text).

As mentioned in one of the comments, this issue was addressed in this answer with regards to JSONP requests from Chrome content scripts and using XHR from a content script.

With regards to Chrome Extensions, they do force you into a sandbox when using the "conten scripts" in a chrome extension. You can remove the dataType: 'jsonp' form the request in the Chrome Extension content script and this call should work. If that does not work, you might trying making the call directly using the XHRHttpRequest:

var xhr = new XMLHttpRequest();
xhr.setRequestHeader("Content-Type", "application/json; charset=utf-8");
xhr.open("POST", $(this).attr('action'), true);
xhr.onreadystatechange = function() {
    if (xhr.readyState == 4) {
       alert("A");
  }
}
xhr.send($(this).serialize());

With regards to other browsers, I am not sure how each of their specific plugin enviroments handle making cross domain XHR calls (or if they even allow it in the first place). This is something that is NOT allowed from normal browsers (unless using something like easyXDM).

Thanks for the answer, i realised now the problem. I just simply add the url of the target site into to permissions list and now it's working with regular AJAX requests fine.

javascript - JSONP communication in a Google Chrome extension - Stack ...

javascript jquery google-chrome-extension jsonp
Rectangle 27 22

You not only might need a manifest, manifest is an absolutely necessary part of any extension. I hate to say that, but you probably need to read a little more about extension structure first, and all your questions will be answered.

  • Overview (what's inside extension and what is manifest)
  • Content Scripts (how to include script into a specific domain with jquery)

(I can provide you an answer if you like, but it would be more beneficial for you to read those links yourself, it's all described and explained there in great details)

chrome://extensions/
{
  "name": "Kiln Hash",
  "version": "1.0.1",
  "description": "Show hash in changeset list in Kiln",
  "content_scripts": [
    {
      "matches": ["https://*.kilnhg.com/*"],
      "js": ["jquery.js", "content_script.js"]
    }
  ]
}
$('[id^=changesetList] tr').each(function () {
    var sid = $(this).attr('sid');
    $(this).find('td span.changesetDescription').append('<span class="csetHash">' + sid + '</span>').css('color','#777');
});

This content script would run on your specified domain after DOM is loaded and jquery is injected.

You don't need a background page for this.

How to make Google Chrome extension to run jQuery Script - Stack Overf...

jquery google-chrome-extension
Rectangle 27 27

The real answer is that you don't need to use "self-running private functions". You need to understand that content scripts are executed in isolation so cannot conflict with resources used by websites by design.

If you want to use a library in your content script the preferred method is to simply include it in your extension/app and then load it first in your manifest;

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

This will result in jquery.js being loaded in to your private content script environment and then myscript.js. Your code will be much cleaner and modular as it doesn't contain minified code for external libraries.

This isn't an issue due to the way content scripts change the JavaScript environment. The execution environment section of the official documentation covers this quite well.

I see that the doc covers exactly the case of jquery : "For example, a content script could include JQuery v1 and the page could include JQuery v2, and they wouldn't conflict with each other."

jQuery itself is just a library and doesn't make any changes that you don't tell it to. Like most libraries common libraries it only exposes its functionality through the use of one or more global variables. If you're using a library that changes the DOM without any instruction you'd probably be aware of it as that behaviour presumably goes hand-in-hand with its functionality.

How to use jQuery in Chrome extensions contentscript without conflict ...

jquery google-chrome google-chrome-extension