I need access to some jQuery methods in my Chrome app, but am unsure how to include the API. I'm new to front-end development and am basically looking for some kind of .h #include
parallel to what I normally do with more C-like languages.
In my manifest.json, I tried adding a path to a downloaded version of jQuery:
{
"name": "my first app",
"manifest_version": 2,
"version": "0.0.1",
"minimum_chrome_version": "36.0.1941.0",
"app": {
"background": {
"scripts": [ "./assets/js/main.js", "./assets/third-party/js/jquery-2.1.1.js"]
}
}
}
In my main.js file:
chrome.app.runtime.onLaunched.addListener(function() {
chrome.app.window.create(
"index.html",
{
innerBounds: {width: 800, height: 510, minWidth: 800}
});
});
In my index.js, I don't have visibility to any width() method:
(function() {
var ui = {
update: null,
};
var initializeWindow = function() {
console.log("Initializing window...");
for (var k in ui) {
var id = k.replace(/([A-Z])/, '-$1').toLowerCase();
var element = document.getElementById(id);
if (!element) {
throw "Missing UI element: " + k;
}
ui[k] = element;
}
ui.update.addEventListener('click', onUpdateClicked);
console.log("done initializing window");
};
var onUpdateClicked = function() {
console.log("update button was clicked");
updateProgressBar(0.25);
};
var updateProgressBar = function(percent) {
var elem = document.getElementById("progressbar");
console.log("Updating progress bar...");
var progress_width = percent * elem.width() / 100;
elem.find('div').animate({ width: progress_width }, 500).html(percent + "% ");
};
window.addEventListener('load', initializeWindow);
}());
Scripts defined in the manifest only apply to background event page (where you probably don't need jQuery at all).
To use jQuery in index.html
, you should reference a local copy of it in a <script>
tag. Be careful to include it in the right order.
That said, there's a problem with your code.
You are mixing up DOM elements and jQuery "elements".
var elem = document.getElementById("progressbar");
returns a DOM element. You can convert it to a jQuery element with $(elem)
, or query the jQuery way instead:
var elem = $("#progressbar");
Once you do that, you'll have access to jQuery methods.
PS I put "elements" in quotation marks because jQuery methods manipulate "sets of matched elements" instead. In this case, a single element matches an id query.
You need to add the path to the downloaded library in your html.
In index.html
, just before your closing body tag:
...
<!-- JavaScript -->
<script src="assets/third-party/js/jquery-2.1.1.js"></script>
</body>
...
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.