Uncaught TypeError: Cannot read property 'checked' of null from chrome.storage.get() - google-chrome-extension

When I try to load my Google Chrome extension into the browser, I get the above error for my options.js file:
Here are my options.js:
var email_addr = document.getElementById("email_addr");
var email_password = document.getElementById("email_password");
var registerButton = document.getElementById("register");
var url = document.getElementById("url");
var port = document.getElementById("port");
var password = document.getElementById("password");
var ecs_mode = document.getElementById("ecs_mode");
var encrypt = document.getElementById("encrypt");
var include_content = document.getElementById("include_content");
var saveButton = document.getElementById("save");
debugger;
restore_settings();
chrome.storage.sync.get({"emailAddr": email_addr.value,
"emailPassword": email_password.value,
"contentServerURL": url.value,
"contentServerPort": port.value,
"contentServerPassword": password.value,
"ecs_mode": ecs_mode.checked,
"encrypt": encrypt.checked,
"include_content": include_content.checked},
function() {
// Update status to let user know settings were saved.
var status = document.getElementById("status");
status.innerHTML = "Settings Saved.";
setTimeout(function() {
status.innerHTML = "";
}, 750);
});
function register_addr() {
}
// Saves settings to chrome.storage.
function save_settings() {
if (!password.value) return;
chrome.storage.sync.set({"emailAddr": email_addr.value,
"emailPassword": email_password.value,
"contentServerURL": url.value,
"contentServerPort": port.value,
"contentServerPassword": password.value,
"ecs_mode": ecs_mode.checked,
"encrypt": encrypt.checked,
"include_content": include_content.checked},
function() {
// Update status to let user know settings were saved.
var status = document.getElementById("status");
status.innerHTML = "Settings Saved.";
setTimeout(function() {
status.innerHTML = "";
}, 750);
});
}
// Restores select box state to saved value from localStorage.
function restore_settings() {
chrome.storage.sync.get("emailAddr", function(val) {
email_addr.value = val.emailAddr;
});
chrome.storage.sync.get("emailPassword", function(val) {
email_password.value = val.emailPassword;
});
chrome.storage.sync.get("contentServerPassword", function(val) {
password.value = val.contentServerPassword;
});
chrome.storage.sync.get("contentServerURL", function(val) {
url.value = val.contentServerURL;
});
chrome.storage.sync.get("contentServerPort", function(val) {
port.value = val.contentServerPort;
});
chrome.storage.sync.get("ecs_mode", function(val) {
ecs_mode.checked = val.ecs_mode;
});
chrome.storage.sync.get("encrypt", function(val) {
encrypt.checked = val.encrypt;
});
chrome.storage.sync.get("include_content", function(val) {
include_content.checked = val.include_content;
});
registerButton.disabled = false;
saveButton.disabled = false;
}
function ecs_mode_fn() {
if (ecs_mode.checked) {
encrypt.disabled = false;
include_content.disabled = false;
}
else {
encrypt.disabled = true;
include_content.disabled = true;
}
}
function toggleButton() {
if (email_addr.value.length == 0) {
registerButton.disabled = true;
saveButton.disabled = true;
}
else {
registerButton.disabled = false;
saveButton.disabled = false;
}
}
document.addEventListener('DOMContentReady', restore_settings);
if (document.querySelector('#save, #ecs_mode, #save, #restore, #register') != null) {
document.querySelector('#ecs_mode').addEventListener('click', ecs_mode_fn);
document.querySelector('#save').addEventListener('click', save_settings);
document.querySelector('#restore').addEventListener('click', restore_settings);
document.querySelector('#email_addr').addEventListener('keyup', toggleButton);
document.querySelector('#register').addEventListener('click', register_addr);
}
options.html:
<html>
<head><title>ECS Extension Settings</title>
<style type="text/css">
body {
width: 800px;
height: 200px;
}
</style>
</head>
<body>
<center><h1>ECS Content Server Settings</h1></center>
<div title="Enter your e-mail address and password here. The address can be a regular Gmail address ('<someone>#gmail.com') or an e-mail address associated with a Google business account.">
<b>Your e-mail address:</b>
<input type="text" id="email_addr">
<b>Password:</b>
<input type="password" id="email_password">
<button id="register" disabled>Register</button>
</div>
<br>
After entering your e-mail address and password, press the <b>Register</b> button to register your address with the ChiaraMail content server. You will then be sent a registration confirmation e-mail containing a link. Select the link to show your content server password and enter the password in the <b>Content server password</b> field below.
<p>
<div title="The name and port number of the content server are fixed. Enter the password you were assigned during registration. You may change your password later at https://www.chiaramail.com/login.jsp">
<b>Content server URL:</b>
<input type="text" id="url" value="www.chiaramail.com" disabled>
<b>Content server port:</b>
<input type="text" id="port" value="443" size="4" disabled>
<b>Content server password:</b>
<input type="password" id="password" maxlength="8" size="8">
<p>
</div>
<div title="Check the 'Send as ECS' box if you want to send e-mail by default using the ECS technology. You will have the option of changing this setting when you compose your message.">
<b>Send as ECS: </b>
<input type="checkbox" id="ecs_mode" checked>
</div>
<div title="Check the 'Encrypt message' box if you want the message to be stored encrypted on the content server. You will have the option of changing this setting when you compose your message.">
<b>Encrypt message: </b>
<input type="checkbox" id="encrypt">
</div>
<div title="Check the 'Include content' box if you want the message content to be sent along with the mail headers (useful when sending to mixed recipients, some enabled for ECS and others who are not). You will have the option of changing this setting when you compose your message.">
<b>Include content: </b>
<input type="checkbox" id="include_content" checked>
</div>
<!--<div title="Select the 'Show ECS users' box to display message senders in magenta if the sender's e-mail address is registered with the ChiaraMail content server. This enables you to know which of your recipients are able to read ECS messages, but setting this option may adversely affect performance.">
<p>
<b>Show ECS users:</b>
<input type="checkbox" id="ecsusers" checked>-->
</div>
<br>
<div id="status"></div>
<div title="Press 'Save settings' to save your settings and 'Restore settings' to display them. Changes made to your account are propagated to all your devices and systems.">
<button id="save" disabled>Save settings</button>
<button id="restore">Restore settings</button>
</div>
<script src="options.js"></script>
</body>
</html>
and manifest.json:
"name": "Envelope-Content Splitting (ECS) Support for Gmail",
"version": "1.0",
"manifest_version": 2,
"description": "Add ECS support for Gmail running in Chrome. This enables Gmail users who access their accounts via the Google Chrome browser to send and read ECS mail. Check out http://www.chiaramail.com for information about ECS and for links to other FREE ECS-enabled mail clients and extensions.",
"browser_action": {
"default_icon": {"19": "ecs_icon_19.png", "38": "ecs_icon_38.png"},
"default_title": "Press here to configure ECS settings",
"default_popup": "options.html"
},
"options_page": "options.html",
"icons": { "16": "ecs_icon_16.png", "48": "ecs_icon_48.png", "128": "ecs_icon_128.png"},
"background": {
"scripts": ["background.js"]
},
"content_scripts": [
{
"run_at": "document_idle",
"matches": ["https://mail.google.com/mail/*"],
"js": ["updateContent.js", "colorHeaders.js", "renderContent.js", "sendOptions.js", "base64.js", "jsaes.js"]
}
],
"permissions": ["tabs",
"activeTab",
"storage",
"https://mail.google.com/mail/*"],
"content_security_policy": "script-src 'self' https://www.chiaramail.com; object-src 'self'"
}
I suspect the problem is with the way I coded chrome.storage.get(), but I couldn't find the API reference, only an example of how to call it. I'm pretty sure I coded the call to chrome.storage.get() correctly, though. What am I missing?

It turns out that I needed to clear the errors after correcting a missing UI element. I don't understand why Google requires users to clear the errors before reloading the extension; the reload should clear them.

Related

Why does my array return no data when creating a customer with the Stripe API in PHP?

I am trying to create both a customer and charge in Stripe.
However, when I try to print_r the array data in my $customer array variable, I get a blank page.
I also tried echoing a string to the charge.php page to make sure the charge page works (echo "page working");, and it does. So I know that's not part of the problem.
The permissions seem to be okay.
These are the permissions for the files in question
-rw-rw-r-- 1 sandbox admin 682 Apr 7 15:55 charge.php
-rw-rw-r-- 1 sandbox admin 1612 Apr 7 17:01 index.php
I have checked my code several times, and no luck.
Can someone help me understand what I might be doing wrong?
Note: The code shown below are all in separate files in the appropriate file types, i.e., all PHP code is in different .php files, and JS in a .js file.
The comment tags are not in the actual code. They are just indicators of where each file starts for the sake of this conversation.
<!-- index.php code below -->
<html>
<body>
<div class="container">
<h2 class="my-4 text-center">Title of Product Page Here</h2>
<form action="./charge.php" method="post" id="payment-form">
<div class="form-row">
<input type="text" class="form-control mb-3 StripeElement StripeElement--empty" name="first_name" placeholder="First Name">
<input type="text" class="form-control mb-3 StripeElement StripeElement--empty" name="last_name" placeholder="Last Name">
<input type="email" class="form-control mb-3 StripeElement StripeElement--empty" name="email" placeholder="Email Address">
<div id="card-element" class="form-control">
<!-- A Stripe Element will be inserted here. -->
</div>
<!-- Used to display form errors. -->
<div id="card-errors" role="alert"></div>
</div>
<button>Submit Payment</button>
</form>
</div>
<script src="https://js.stripe.com/v3/"></script>
<script src="js/charge.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</body>
</html>
<!-- charge.php code below -->
<!-- Note: Both the Stripe test Key and Stripe PW were masked per Stripe recommendation. Actual test key and password used in real code -->
<?php
require_once('vendor/autoload.php');
\Stripe\Stripe::setApiKey('sk_test_################');
// Sanitize
$POST = filter_var_array($_POST, FILTER_SANITIZE_STRING);
$first_name = $POST['first_name'];
$last_name = $POST['last_name'];
$email = $POST['email'];
$token = $POST['stripeToken'];
// Create customer
$customer = \Stripe\Customer::create(array(
"email" => $email,
"source" => $token
));
// Charge customer
$charge = \Stripe\Charge::create(array(
"amount" => 5000,
"currency" => "usd",
"description" => "Audio Loops Pack 2019",
"customer" => $customer->id
));
print_r($customer);
<!-- charge.js code below -->
// Create a Stripe client.
var stripe = Stripe('pk_test_################');
// Create an instance of Elements.
var elements = stripe.elements();
// Custom styling can be passed to options when creating an Element.
// (Note that this demo uses a wider set of styles than the guide below.)
var style = {
base: {
color: '#32325d',
fontFamily: '"Helvetica Neue", Helvetica, sans-serif',
fontSmoothing: 'antialiased',
fontSize: '16px',
'::placeholder': {
color: '#aab7c4'
}
},
invalid: {
color: '#fa755a',
iconColor: '#fa755a'
}
};
//Style button
document.querySelector('#payment-form button').classList ='btn btn-primary btn-block mt-4';
// Create an instance of the card Element.
var card = elements.create('card', {style: style});
// Add an instance of the card Element into the `card-element` <div>.
card.mount('#card-element');
// Handle real-time validation errors from the card Element.
card.addEventListener('change', function(event) {
var displayError = document.getElementById('card-errors');
if (event.error) {
displayError.textContent = event.error.message;
} else {
displayError.textContent = '';
}
});
// Handle form submission.
var form = document.getElementById('payment-form');
form.addEventListener('submit', function(event) {
event.preventDefault();
stripe.createToken(card).then(function(result) {
if (result.error) {
// Inform the user if there was an error.
var errorElement = document.getElementById('card-errors');
errorElement.textContent = result.error.message;
} else {
// Send the token to your server.
stripeTokenHandler(result.token);
}
});
});
// Submit the form with the token ID.
function stripeTokenHandler(token) {
// Insert the token ID into the form so it gets submitted to the server
var form = document.getElementById('payment-form');
var hiddenInput = document.createElement('input');
hiddenInput.setAttribute('type', 'hidden');
hiddenInput.setAttribute('name', 'stripeToken');
hiddenInput.setAttribute('value', token.id);
form.appendChild(hiddenInput);
// Submit the form
form.submit();
}
I expected the customer and charge arrays to return data, but I get nothing on the screen, not even an empty array.

Unobtrusive validation with Jquery Steps Wizard

Recently I asked a question for how to customize the JQuery Steps as I wanted to use partial views instead of static content. I have partially solved that problem by using the following code supported by jquery-steps,
<h3>Step 1</h3>
<section data-mode="async" data-url="/Formation/RenderStep1"></section>
<h3>Step 2</h3>
<section data-mode="async" data-url="/Formation/RenderStep2"></section>
Now the big problem I am facing right now is how to use unobtrusive validation. I don't want to use JQuery custom validation and there must be some way of using Obtrusive with it.
Each partial view that is rendered has its own form. I want to validate the form in the onStepChanging function of jquery-steps,
$("#my-steps").steps({
headerTag: "h3",
bodyTag: "section",
contentMode: "async",
transitionEffect: "fade",
stepsOrientation: "vertical",
onStepChanging: function (event, currentIndex, newIndex) {
return true;
}
});
I have tried calling $.validator.unobtrusvie.parse('#myform'); in the onStepChanging function but ('#myform') is undefined and still I don't know that whether this is the right way to call the unobtrusive validation manually. Kindly guide me and show me the direction to achieve this. Any help will be highly appreciated.
It sounds like your trying manage multiple forms within the JQuery Steps library and I don't think that is what its intended for.
When you configure JQuery Steps, you set it up against the form in your view.
Unobtrusive JQuery Validation is looking at the model in your view and automatically configuring the HTML with the relevant data attributes for error handling.
This validation should be firing at the client side automatically.
There shouldn't be a problem with using Partial View's, as long as there encapsulated within the same form element.
What is the requirement to have each partial view wrapped in its own form? If your trying to make multiple posts throughout the JQuery Steps form wizard, your defeating the object.
At each step in the JQuery Steps form, your only validating the one form like this :-
onStepChanging: function (event, currentIndex, newIndex) {
//Allways allow user to move backwards.
if (currentIndex > newIndex) {
return true;
}
// Remove the validation errors from the next step, incase user has previously visited it.
var form = $(this);
if (currentIndex < newIndex) {
// remove error styles
$(".body:eq(" + newIndex + ") label.error", form).remove();
$(".body:eq(" + newIndex + ") .error", form).removeClass("error");
}
//disable validation on fields that are disabled or hidden.
form.validate().settings.ignore = ":disabled,:hidden";
return form.valid();
}
Once the user has finished entering data, and the client side validation has been met, you hook into the onFinished method and post the form :-
onFinished: function (event, currentIndex) {
var form = $(this);
form.submit();
}
The purpose of JQuery Steps is to allow the user to have a fluid experience of filling out a form and to not be overwhelmed with the number of questions been asked.
From the developers perspective, it enables us to split up the form into nice size-able chunks without having to worry about saving progress between screens or losing the state of the form data and allows us to capture all of the required data with only having to make that one post once all validation criteria has been met.
I tried the formvalidation plugin, it will relax your mind from searching in validation without form tag or validation without submit the form that's the issue I solved when I tried it.
I know it's not free but you can try it from here, personally I like it
First update height after validation
<style type="text/css">
/* Adjust the height of section */
#profileForm .content {
min-height: 100px;
}
#profileForm .content > .body {
width: 100%;
height: auto;
padding: 15px;
position: relative;
}
Second, add data-steps index to your section*
<form id="profileForm" method="post" class="form-horizontal">
<h2>Account</h2>
<section data-step="0">
<div class="form-group">
<label class="col-xs-3 control-label">Username</label>
<div class="col-xs-5">
<input type="text" class="form-control" name="username" />
</div>
</div>
<div class="form-group">
<label class="col-xs-3 control-label">Email</label>
<div class="col-xs-5">
<input type="text" class="form-control" name="email" />
</div>
</div>
<div class="form-group">
<label class="col-xs-3 control-label">Password</label>
<div class="col-xs-5">
<input type="password" class="form-control" name="password" />
</div>
</div>
<div class="form-group">
<label class="col-xs-3 control-label">Retype password</label>
<div class="col-xs-5">
<input type="password" class="form-control" name="confirmPassword" />
</div>
</div>
</section>
Third, javascript code
<script>
## // to adjust step height to fit frame after showing validation messages##
$(document).ready(function() {
function adjustIframeHeight() {
var $body = $('body'),
$iframe = $body.data('iframe.fv');
if ($iframe) {
// Adjust the height of iframe
$iframe.height($body.height());
}
}
// IMPORTANT: You must call .steps() before calling .formValidation()
$('#profileForm')
// setps setup
.steps({
headerTag: 'h2',
bodyTag: 'section',
onStepChanged: function(e, currentIndex, priorIndex) {
// You don't need to care about it
// It is for the specific demo
adjustIframeHeight();
},
// Triggered when clicking the Previous/Next buttons
// to apply validation to your section
onStepChanging: function(e, currentIndex, newIndex) {
var fv = $('#profileForm').data('formValidation'), // FormValidation instance
// The current step container
$container = $('#profileForm').find('section[data-step="' + currentIndex +'"]');
// Validate the container
fv.validateContainer($container);
var isValidStep = fv.isValidContainer($container);
if (isValidStep === false || isValidStep === null) {
// Do not jump to the next step
return false;
}
return true;
},
// Triggered when clicking the Finish button
onFinishing: function(e, currentIndex) {
var fv = $('#profileForm').data('formValidation'),
$container = $('#profileForm').find('section[data-step="' + currentIndex +'"]');
// Validate the last step container
fv.validateContainer($container);
var isValidStep = fv.isValidContainer($container);
if (isValidStep === false || isValidStep === null) {
return false;
}
return true;
},
onFinished: function(e, currentIndex) {
// Uncomment the following line to submit the form using the defaultSubmit() method
// $('#profileForm').formValidation('defaultSubmit');
// For testing purpose
$('#welcomeModal').modal();
}
})
.formValidation({
framework: 'bootstrap',
icon: {
valid: 'glyphicon glyphicon-ok',
invalid: 'glyphicon glyphicon-remove',
validating: 'glyphicon glyphicon-refresh'
},
// This option will not ignore invisible fields which belong to inactive panels
excluded: ':disabled',
fields: {
username: {
validators: {
notEmpty: {
// for asp.net i used element attribute to integerated with unobtrusive validation
// message :$('username').attr('data-val-required')
message: 'The username is required'
},
stringLength: {
min: 6,
max: 30,
message: 'The username must be more than 6 and less than 30 characters long'
},
regexp: {
regexp: /^[a-zA-Z0-9_\.]+$/,
message: 'The username can only consist of alphabetical, number, dot and underscore'
}
}
},
email: {
validators: {
notEmpty: {
message: 'The email address is required'
},
emailAddress: {
message: 'The input is not a valid email address'
}
}
},
password: {
validators: {
notEmpty: {
message: 'The password is required'
},
different: {
field: 'username',
message: 'The password cannot be the same as username'
}
}
},
confirmPassword: {
validators: {
notEmpty: {
message: 'The confirm password is required'
},
identical: {
field: 'password',
message: 'The confirm password must be the same as original one'
}
}
}
}
});

jQuery validation engine using the “ajax[selector]”

I have the following (multistep form) HTML:
<form id="myform">
<fieldset id="first_step">
<input type="text" name="register" placeholder="Αρ. Μητρώου" id="register" class="validate[required,custom[integer]]" />
<input type="text" name="email" placeholder="Πόλη" id="city" class="validate[required,ajax[email]]" />
<input type="button" name="next" class="next action-button" value="Επόμενο" id="next1" />
</fieldset>
<fieldset id="second_step">
....
....
....
</fieldset>
</form>
The instantiation js code plus logic (myform.js)
$(document).ready(function(){
var first_step = $("#first_step");
var second_step = $("#second_step");
$("#myform").validationEngine('attach', {
promptPosition : "centerRight",
scroll: false
});
$("#next1").on('click', function (e) {
e.preventDefault();
var valid = $("#myform").validationEngine('validate');
if (valid == true) {
second_step.show();
} else {
$("#ithemiscustomerform").validationEngine();
}
});
});
The rules “validationEngine-el.js”
(function($){
$.fn.validationEngineLanguage = function(){
};
$.validationEngineLanguage = {
newLang: function(){
$.validationEngineLanguage.allRules = {
"required": { // Add your regex rules here, you can take telephone as an example
"regex": "none",
"alertText": "* Υποχρεωτικό πεδίο",
"alertTextCheckboxMultiple": "* Παρακαλώ επιλέξτε",
"alertTextCheckboxe": "* Υποχρεωτικό πεδίο",
"alertTextDateRange": "* Και τα δύο πεδία ημ/νίας είναι υποχρεωτικά"
},
// --- CUSTOM RULES -- Those are specific to the demos, they can be removed or changed to your likings
"email": {
"url": "http://localhost/userformServer/validator.cfc?method=valEmail",
// you may want to pass extra data on the ajax call
//"extraData": "name=eric",
"alertText": "* Μη έγκυρο email",
"alertTextLoad": "* Παρακαλώ περιμένετε...",
"alertTextOk": "* Το eimail είναι διαθέσιμο"
},
"integer": {
"regex": /^[\-\+]?\d+$/,
"alertText": "* Μη έγκυρος ακέραιος"
}
};
}
};
$.validationEngineLanguage.newLang();
})(jQuery);
The problem
Remote validation works great for the “email” field “on blur” –while user completing the form. But when I click the “next1” button to move on the next fieldset (“second_step”) even if the email field is valid (remotely valid) the form doesn’t move to the next fieldset (see “myform.js” onclick). Specifically when I call “$("#myform").validationEngine('validate');” inside the click event it returns false. I think this occurs due the asynchronous nature of validation. Is there any workaround for this?

Why can't play youtube chromeless player in chrome extension? [duplicate]

I'm newbie at chrome extension. I'm making chrome extension that play youtube chromeless player.
It worked on chrome web browser. But, it isn't working on chrome extension.
I tested local .swf file. That is worked on chrome extension.
I think, chrome extension can't call onYouTubePlayerReady().
So I called window.onYouTubePlayerReady() after swfobject.embedSWF(). But, it isn't worked at ytplayer.loadVideoById("xa8TBfPw3u0", 0); with error message.
The error message was Uncaught TypeError: Object #<HTMLObjectElement> has no method 'loadVideoById'.
Is there a problem in manifest.json? Or in YouTube API? I don't know why isn't working on chrome extension.
popup.html is
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>YouTube Play</title>
</head>
<body>
<table width="1000" height="390">
<tr>
<td>
<div id="videoDiv">
Loading...
</div></td>
<td valign="top">
<div id="videoInfo">
<p>
Player state: <span id="playerState">--</span>
</p>
<p>
Current Time: <span id="videoCurrentTime">--:--</span> | Duration: <span id="videoDuration">--:--</span>
</p>
<p>
Bytes Total: <span id="bytesTotal">--</span> | Start Bytes: <span id="startBytes">--</span> | Bytes Loaded: <span id="bytesLoaded">--</span>
</p>
<p>
Controls: <input type="button" id="play" value="Play" />
<input type="button" id="pause" value="Pause" />
<input type="button" id="mute" value="Mute" />
<input type="button" id="unmute" value="Unmute" />
</p>
<p>
<input id="volumeSetting" type="text" size="3" />
<input type="button" id="setVolume" value="Set Volume" /> | Volume: <span id="volume">--</span>
</p>
</div></td>
</tr>
</table>
<script type="text/javascript" src="jsapi.js"></script>
<script type="text/javascript" src="my_script.js"></script>
<script type="text/javascript" src="swfobject.js"></script>
</body>
</html>
manifest.json is
{
"manifest_version": 2,
"name": "YouTube Player",
"description": "This extension is YouTube Player",
"version": "1.0",
"browser_action": {
"default_icon": "icon.png",
"default_popup": "popup.html"
},
"permissions": ["tabs", "http://*/*", "https://*/*", "background"],
"content_scripts": [
{
"matches": ["http://www.youtube.com/*"],
"js": ["my_script.js", "swfobject.js", "jsapi.js"]
}
]
}
my_script.js is
/*
* Chromeless player has no controls.
*/
// Update a particular HTML element with a new value
function updateHTML(elmId, value) {
document.getElementById(elmId).innerHTML = value;
}
// This function is called when an error is thrown by the player
function onPlayerError(errorCode) {
alert("An error occured of type:" + errorCode);
}
// This function is called when the player changes state
function onPlayerStateChange(newState) {
updateHTML("playerState", newState);
}
// Display information about the current state of the player
function updatePlayerInfo() {
// Also check that at least one function exists since when IE unloads the
// page, it will destroy the SWF before clearing the interval.
if (ytplayer && ytplayer.getDuration) {
updateHTML("videoDuration", ytplayer.getDuration());
updateHTML("videoCurrentTime", ytplayer.getCurrentTime());
updateHTML("bytesTotal", ytplayer.getVideoBytesTotal());
updateHTML("startBytes", ytplayer.getVideoStartBytes());
updateHTML("bytesLoaded", ytplayer.getVideoBytesLoaded());
updateHTML("volume", ytplayer.getVolume());
}
}
// Allow the user to set the volume from 0-100
function setVideoVolume() {
var volume = parseInt(document.getElementById("volumeSetting").value);
if (isNaN(volume) || volume < 0 || volume > 100) {
alert("Please enter a valid volume between 0 and 100.");
} else if (ytplayer) {
ytplayer.setVolume(volume);
}
}
function playVideo() {
if (ytplayer) {
ytplayer.playVideo();
}
}
function pauseVideo() {
if (ytplayer) {
ytplayer.pauseVideo();
}
}
function muteVideo() {
if (ytplayer) {
ytplayer.mute();
}
}
function unMuteVideo() {
if (ytplayer) {
ytplayer.unMute();
}
}
// This function is automatically called by the player once it loads
function onYouTubePlayerReady(playerId) {
ytplayer = document.getElementById("ytPlayer");
// This causes the updatePlayerInfo function to be called every 250ms to
// get fresh data from the player
setInterval(updatePlayerInfo, 250);
updatePlayerInfo();
ytplayer.addEventListener("onStateChange", "onPlayerStateChange");
ytplayer.addEventListener("onError", "onPlayerError");
//Load an initial video into the player
ytplayer.loadVideoById("xa8TBfPw3u0", 0);
}
// The "main method" of this sample. Called when someone clicks "Run".
function loadPlayer() {
// Lets Flash from another domain call JavaScript
var params = {
allowScriptAccess : "always"
};
// The element id of the Flash embed
var atts = {
id : "ytPlayer"
};
// All of the magic handled by SWFObject (http://code.google.com/p/swfobject/)
swfobject.embedSWF("http://www.youtube.com/apiplayer?" + "&enablejsapi=1&playerapiid=ytplayer", "videoDiv", "640", "390", "8", null, null, params, atts);
//window.onYouTubePlayerReady();
document.getElementById("play").onclick = playVideo;
document.getElementById("pause").onclick = pauseVideo;
document.getElementById("mute").onclick = muteVideo;
document.getElementById("unmute").onclick = unMuteVideo;
document.getElementById("setVolume").onclick = setVideoVolume;
}
function _run() {
loadPlayer();
}
google.setOnLoadCallback(_run);
Please help me.
Recently I've encountered the same issue when working on a Chrome extension. When testing, the calls are simply not triggered. Until I've read this:
To test any of these calls, you must have your file running on a webserver, as the Flash player restricts calls between local files and the internet.
From YouTube's Player API Documentation

Geolocation JSF

Does anyone have an example of sending a geolocation from a mobile phone to a JSF backing bean?
Would like to get the customers address using geolocation? (Will need to convert from geolocation co-ordinates to a drop down list of nearby roads).
Thanks,
D
Not sure if this will help u get started...
This pulls GPS Geolocation Data from Mobile Devices into a Form...
Then do whatever with it from there...
<script type="text/javascript">
function getLocationConstant()
{
if(navigator.geolocation)
{
navigator.geolocation.getCurrentPosition(onGeoSuccess,onGeoError);
} else {
alert("Your browser or device doesn't support Geolocation");
}
}
// If we have a successful location update
function onGeoSuccess(event)
{
document.getElementById("Latitude").value = event.coords.latitude;
document.getElementById("Longitude").value = event.coords.longitude;
}
// If something has gone wrong with the geolocation request
function onGeoError(event)
{
alert("Error code " + event.code + ". " + event.message);
}
</script>
<cfform action="gps2.cfm" method="post">
Latitude: <input type="text" id="Latitude" name="Latitude" value="">
<br><br>
Longitude: <input type="text" id="Longitude" name="Longitude" value="">
<br><br>
<input type="button" value="Get Location" onclick="getLocationConstant()"/>
<br><br>
<input type="submit" value="Add GPS Location" class=small>
</cfform>
View this links please:
https://developers.google.com/maps/documentation/javascript/examples/map-geolocation - Google Developers
https://goo.gl/TD7aiq - JsFiddle
JS:
// Note: This example requires that you consent to location sharing when
// prompted by your browser. If you see the error "The Geolocation service
// failed.", it means you probably did not give permission for the browser to
// locate you.
function initMap() {
var map = new google.maps.Map(document.getElementById('map'), {
center: {lat: -34.397, lng: 150.644},
zoom: 6
});
var infoWindow = new google.maps.InfoWindow({map: map});
// Try HTML5 geolocation.
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
var pos = {
lat: position.coords.latitude,
lng: position.coords.longitude
};
infoWindow.setPosition(pos);
infoWindow.setContent('Location found.');
map.setCenter(pos);
}, function() {
handleLocationError(true, infoWindow, map.getCenter());
});
} else {
// Browser doesn't support Geolocation
handleLocationError(false, infoWindow, map.getCenter());
}
}
function handleLocationError(browserHasGeolocation, infoWindow, pos) {
infoWindow.setPosition(pos);
infoWindow.setContent(browserHasGeolocation ?
'Error: The Geolocation service failed.' :
'Error: Your browser doesn\'t support geolocation.');
}
Using the Javascript you can get the co-ordinates and you can set the backend variable using document.getElementById("id")) in javascript.
Example:
<h:inputText value="{myBean.latitude}" id="latitudeID" />
<!DOCTYPE html>
<html>
<body>
<p>Click the button to get your coordinates.</p>
<button onclick="getLocation()">Try It</button>
<p id="demo"></p>
<script>
var x = document.getElementById("demo");
function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition);
} else {
x.innerHTML = "Geolocation is not supported by this browser.";
}
}
function showPosition(position) {
x.innerHTML = "Latitude: " + position.coords.latitude +
"<br>Longitude: " + position.coords.longitude;
document.getElementById("formName:latitudeID").value=position.coords.latitude; /* this will set the value in variable */
}
</script>
</body>
</html>

Resources