I'm building my first Chrome extension. It's a very simple thing I'm trying to do at this point so I can try and gain an understanding of how it works and build off of that.
Anyway what I am trying to do right now is I have a extension button that opens up a page with a TEXTAREA. I want the user to be able to enter text into this textarea box and save this to be called later (this setting also needs to be available to be called again the next time Chrome is opened, whatever they enter into this textbox I want to keep that value permanently unless they save over it).
My TEXTAREA id=test1
Here's my JavaScript
function saveSettings() {
var storage = chrome.storage.sync;
// Get signature value from text box
var txtValue = test1.value;
// Save using Chrome storage API
storage.set(txtValue, function() {
console.log("Saved");
});
}
function insertText(text) {
document.getElementById("test1").value= text;
}
For testing purposes I have a addEventListener for inserting a set text value to make sure the insert function works. I have a button for a hard coded set of text, then another button to try to insert the "saved" text which should be the var txtValue.
The insert function that WORKS
document.addEventListener('DOMContentLoaded', function() {
var temp = document.getElementById('template');
temp.addEventListener('click', function() {
insertText('Hard Coded Text');
message('Template Inserted');
});
});
The insert function that does NOT work that is trying to insert the value typed into and saved into the TEXTAREA field.
document.addEventListener('DOMContentLoaded', function() {
var link = document.getElementById('insert');
link.addEventListener('click', function() {
insertText(txtValue);
message('Saved Text Inserted');
});
});
I'm not sure what I'm doing wrong. I've looked at a bunch of different examples and most of them are similar to what I've done using storage.sync but I can't seem to get it to work.
Any thoughts would be greatly appreciated.
Thank you!
to save
chrome.storage.sync.set({ mytext: txtValue });
to get
chrome.storage.sync.get('mytext', function(data) {
yourTextArea.value = data.mytext;
});
I found a new library to call chrome storage with Promise, pretty cool.
https://github.com/Selection-Translator/chrome-call
import { scope } from 'chrome-call'
const storage = scope('storage.local')
storage('get', 'flows').then(data => initFlows(data.flows))
Related
I am developing a component in joomla 3 and it's my first time. This component is for desk reservation in a restaurant. I have a from which user should select a date and time to be able to see available desks.So after selecting the date and time I have used a button(seeavail) to show available desks.
My problem is that I don't know how to keep entered data in the form and reload the page.
First I tried to use javascript as below, but beforeunload event doesn't happen.
jQuery(document).ready(function () {
jQuery("#seeavail").click(function(){
location.reload();
});
jQuery(window).on('beforeunload', function() {
localStorage.setItem("name", jQuery('#customername').text());
alert( "beforeonload");
});
jQuery(window).on('load', function() {
var name = localStorage.getItem("name");
if (name !== null) jQuery('#customername').text("abs");
alert( "load");
});
});
Then I thought I should use Joomla $session->set and get ,as I searched more or maybe get method. Right now I am confused and any help in simple words and samples is appropriated.
I'm using iAd producer to create HTML widgets for iBooks I'm making using iBooks Author. I've done some research and learned that I can have user input saved into local storage by way of a variable that is called every time the widget is opened. This is great except for the new problem of having to create hundreds of text box widgets all with different variables so I can use these text boxes on multiple pages. Is there a way for me to automate this using Java Script? One idea I had was to use a "while" function to tell the script to ++ the variable if the one it tried to use was not empty. Example: the variable "001" was already used so the code would ideally set the next user text to variable "002". Preferably, I'd like to be able to create one widget with this code that I could reuse anywhere else.
Here is the code I'm currently using:
/*Widget code*/
this.onViewControllerViewWillAppear = function (event) {
var theValue = this.outlets.textField;
if (localStorage.getItem("theKey102") === null) {
theValue.value = "";
} else {
theValue.value = localStorage.getItem("theKey102");
}
};
/*This is the code for one of the text boxes I'm using */
this.onControlValueChange = function (event) {
var theValue = this.viewController.outlets.textField;
localStorage.setItem("theKey102", theValue.value);
};
I have a filter_horizontal selector in my Django admin that has a list of categories for products (this is on a product page in the admin). I want to change how the product change form looks based on the category or categories that are chosen in the filter_horizontal box.
I want to call a function every time a category is moved from the from or to section of the filter_horizontal.
What I have now is:
(function($){
$(document).ready(function(){
function toggleAttributeSection(choices) {
$.getJSON('/ajax/category-type/', { id: choices}, function (data, jqXHR) {
// check the data and make changes according to the choices
});
}
// The id in the assignment below is correct, but maybe I need to add option[]??
var $category = $('#id_category_to');
$category.change(function(){
toggleAttributeSection($(this).val());
});
});
})(django.jQuery);
The function never gets called when I move categories from the left side to the right side, or vice versa, of the filter_horizontal.
I assume that $category.change() is not correct, but I don't know what other events might be triggered when the filter_horizontal is changed. Also, I know there are multiple options inside of the select box. I haven't gotten that far yet, but how do I ensure all of them are passed to the function?
If anyone can point me in the right direction I would be very grateful. Thank!
You need to extend the SelectBox.redisplay function in a scope like so:
(function() {
var oldRedisplay = SelectBox.redisplay;
SelectBox.redisplay = function(id) {
oldRedisplay.call(this, id);
// do something
};
})();
Make sure to apply this after SelectBox has been initialized on the page and every time a select box refreshes (option moves, filter is added, etc.) your new function will be called.
(Code courtesy of Cork on #jquery)
I finally figured this out. Here is how it is done if anyone stumbles on this question. You need to listen for change events on both the _from and _to fields in the Django filter_horizontal and use a timeout to allow the Django javascript to finish running before you pull the contents of the _from or _to fields. Here is the code that worked for me:
var $category = $('#id_category_to');
$category.change(function(){
setTimeout(function () { toggleAttributeSection(getFilterCategoryIds()) }, 500);
});
var $avail_category = $('#id_category_from');
$avail_category.change(function(){
setTimeout(function () { toggleAttributeSection(getFilterCategoryIds()) }, 500);
});
And this is how I get the contents of the _to field:
function getFilterCategoryIds() {
var x = document.getElementById("id_category_to");
var counti;
var ids = [];
for (counti = 0; counti < x.length; counti++) {
ids.push(x.options[counti].value);
}
return ids;
}
I know it was a convoluted question and answer and people won't come across this often but hopefully it helps someone out.
Context:
I work a student job transcribing paper reports in a webapp. It's old and we unfortunately can't change the source nor directly run a DB query.
It only checks if the unique ID exists once you submit the entire form, and you can't submit it unless it's entirely filled. Needless to say, it's a huge waste of time as you often transcribe the whole thing only to realise it's a duplicate.
Objective:
I made the userscript below that launches a search the search on the onblur of the unique ID's input(noReferenceDeclarant), checks if there are any matches (rows) and returns accordingly. Runs with Greasemonkey. The search form is in another page on the same domain. The search form does not take any URL arguments.
Can this be done without using an iframe (AJAX perhaps?)
This is a tool for my own productivity & to learn JS at the same time. As I'm still very much a beginner, any tips to make that code cleaner are welcome.
//Adding function to input's blur event
$(document).on ("blur", "#noReferenceDeclarant", isRefNumberExists);
//Vars
var noReferenceDeclarant = '';
var loadCode = 0;
var $searchForm;
//Fonctions
function isRefNumberExists ()
{
noReferenceDeclarant = $('#noReferenceDeclarant').val();
loadCode = 0;
//Make sure there's data in the input before proceeding
if (noReferenceDeclarant)
{
//Build search iframe
$searchForm = $('<iframe />', {
name: 'searchWindow',
src: 'rechercherGriIntranet.do?methode=presenterRechercher',
id: 'searchWindow',
width: 0,
height: 0
}).appendTo('body');
$searchForm.load(searchRefNumber);
}
}
function searchRefNumber()
{
var isExists = false;
//Check which "load" it is to avoid submit loops
if (loadCode === 0)
{
loadCode = 1;
//Filling search form with search term
$(this.contentDocument).find('#noReference').val(noReferenceDeclarant);
//Set search form preferences
$(this.contentDocument).find('#typeRapportAss').prop('checked', false);
$(this.contentDocument).find('#typeRapportAS').prop('checked', false);
$(this.contentDocument).find('#typeRapportSI').prop('checked', true);
//Submit the form
$(this.contentDocument).find('form:first').submit();
}
else if (loadCode === 1)
{
loadCode = 2;
//See if there are any tr in the result table. If there are no results, there a thead but no tr.
var foundReports = $(this.contentDocument).find('.resultatRecherche tr').length;
if (foundReports > 0)
{
if (confirm('A report matching this ID already exists. Do you want to display it?'))
{
//Modal window loading the report in an iframe. Not done yet but that's fairly straightforward.
}
else
{
//Close and return to the form.
}
}
}
//Reset variables/clean ressources
delete $searchForm;
$('#dateRedactionRapport').focus();
}
On the whole I've seen far, far worse code.
Ajax could do it, but then you'd just have to put the AJAX response into the DOM (as an iframe, most likely).
In this instance, I'd keep the approach you have. I think it is the sanest.j
Without the full context, there may be a way to clean up the loadCode -- but what you have is pretty same and works. A lot of folks would call it a semaphore, but that is just an issue of terminology.
The only thing I"d really clean up is recommend not calling the jQuery object so often..
// Many folks recommend that jQuery variables be named $<something>
var $doc = $(this.contentDocument);
doc.find('#typeRapportAss').prop('checked', false);
$doc.find('#typeRapportAS').prop('checked', false);
$doc.find('#typeRapportSI').prop('checked', true);
If you wanted to play with jQuery data structures, you could make a 'config' object that looks like this:
var formValues = {
typeRapportAs: false,
typeRapportAS: false,
typeRapportSI: true
};
then iterate over that to (using for ... in with .hasOwnProperty).
Not NEEDED for this project, what you are doing is fine, but it might make a learning exercise.
I am making a webapp, that uses mobiscroll as a number counter. The numbers are saved via a submit button below it. The problem I have is whenever the user presses the home button, when the webapp is reloaded, it resets the number list. I figured it would be a good idea to save the value to localstorage,and recall it when the app is reopened. Now that's where I am stuck.
Here is the function for the button press that works fine:
<script type="text/javascript">
function save_it() {
//Save the scroll value for later
var scrollsave = $('#i').scroller('getValue');
localStorage.setItem("scrollsave", scrollsave);
localStorage.saveServer
}
</script>
I have a function further up, that is giving me trouble, and refusing to work proper, I have tried the following methods:
My first attempt to assign
<script type="text/javascript">
$(function () {
var scrollstate = localStorage["scrollsave"];
if (scrollstate != null) {
$('#i').scroller('setValue', scrollstate);
}
});
</script>
I get an error of, Object x,x,x,x has no method 'join'.
Second attempts to convert to array and back, but no luck.
var oldscroll = localStorage.getItem["scrollsave"];
var finalsaved = SON.parse(oldscroll);
if (finalsaved != null) {
$('#i').scroller('setValue', finalsaved);
The documentaion on mobiscroll is here http://docs.mobiscroll.com/22/mobiscroll-core . And it says, "scroller values from the data parameter passed as array".
My key, scrollsave is stored with a value of 1,2,1,1 . Which seems to meet the correct formatting to throw into the mobiscroll part.
I have a feeling there is something trivial I am overlooking, but I can't figure out what.
var oldscroll = localStorage.getItem["scrollsave"]; should be var oldscroll = localStorage.getItem("scrollsave");