How to deliver value from popup.js to background.js - javascript

I hope to deliver the value from popup.js to background.js so that I can open the website as what i expect. I use the localStorage variable as my json's value. But when found that the value I have delieverd to background.js in the argument input of the function openTab(input) is always the string "localStorage.input" itself. How can I solve it?
popup.js
window.onload=function()
{
localStorage.input=document.getElementById("search").value;
document.getElementById("submit").onclick=function()
{
chrome.extension.sendMessage({command:"start",input:localStorage.input});
}
}
background.js
chrome.runtime.onMessage.addListener(
function(request,sender,sendResponse)
{
switch(request.command)
{
case "start":
openTab(request.input);
break;
}
return true;
}
);
var openTab=function(input)
{
chrome.windows.create
(
{
url:"http://www.baidu.com/s?wd="+input,
}
);
};

try this out
var lStore = localStorage.input || '';
window.onload=function()
{
var search = document.getElementById("search");
search.value = lStore
document.getElementById("submit").onclick=function()
{
// var input = search.value; //try this as well
var input = lStore;
chrome.extension.sendMessage({command:"start",input:input});
}
}

Related

Get async variable return empty

I am trying to create an add-in for the outlook windows application.
The following code should copy the email body to the clipboard, but it doesn't do that.
I need to press the run button two times in order to get the content copied, but I need to copy the content from the first time!
What is wrong with my code?
var messageBody = "";
export async function run() {
Office.context.mailbox.item.body.getAsync(
Office.CoercionType.Text,
function (asyncResult) {
if (asyncResult.status !== Office.AsyncResultStatus.Succeeded) {
messageBody = asyncResult.error;
} else {
messageBody = asyncResult.value;
}
});
copyToClipboard(messageBody)
}
function copyToClipboard(text) {
var copyhelper = document.createElement("input");
copyhelper.className = 'copyhelper'
document.body.appendChild(copyhelper);
copyhelper.value = text;
copyhelper.select();
document.execCommand("copy");
document.body.removeChild(copyhelper);
}

jQuery/JavaScript operator equal SQL LIKE %Example%

Is there any way to search a specific part on my input with Javascript/jQuery?
Tried to do with 2 different ways, but no results for that
<script type="text/javascript">
$("#button").click(function () {
$("#DivToToggle").toggle();
var campo = document.getElementById('FieldToSearch');
if (campo.contains("Test")) {
document.getElementById('FieldToWrite').value = "123";
}
else {
document.getElementById('FieldToWrite').value = "456";
}
});
and
<script type="text/javascript">
$("#button").click(function () {
$("#DivToToggle").toggle();
var field = document.getElementById('FieldToSearch');
if (field.match(/Test.*/)) {
document.getElementById('FieldToWrite').value = "123";
}
else {
document.getElementById('FieldToWrite').value = "456";
}
});
#EDIT
Thanks to #TalhaAbrar, found the correct way to do it.
<script type="text/javascript">
$("#button").click(function () {
var field = document.getElementById('FieldToSearch').value;
if (field.indexOf("Test")) {
$("#DivToToggle").toggle();
document.getElementById('FieldToWrite').value = "123";
}
else {
$("#DivToToggle").toggle();
document.getElementById('FieldToWrite').value = "456";
}
});
Try to fetch the value of search field like document.getElementById('FieldToSearch').value and then use function indexOf in your if statement, that should work for you.
example code:
var field = document.getElementById('FieldToSearch').value;
if (field.indexOf("value_to_check")) {
// true if exists
} else {
// false if doesn't
}
I think you need to check the value of the field, e.g.
var campo = document.getElementById('FieldToSearch').value;
...
And then use includes(), e.g.
if (campo.includes("Test")) {
...

How to simplify testing a string against multiple regexes

I want to validate if string is spotify or youtube or invalid URL. This works, but it seems it could be done simpler. How can I make it more efficient?
String.prototype.spotifyUrl = function() {
return this.match(/^(spotify:|https:\/\/[a-z]+\.spotify\.com\/)/);
}
String.prototype.youtubeUrl = function() {
return this.match(/^(?:https?:\/\/)?(?:www\.)?(?:youtu\.be\/|youtube\.com\/(?:embed\/|v\/|watch\?v=|watch\?.+&v=))((\w|-){11})(?:\S+)?$/);
}
function validateUrl (url) {
if ( url.spotifyUrl() ) {
alert('spotify');
}
else if ( url.youtubeUrl() ) {
alert('youtube');
}
else {
alert('invalid url');
}
};
validateUrl('https://open.spotify.com/track/3JiockjOTd8m2VGcTGkmew');
JS Fiddle
You could make an object with a property per site you want to recognise:
var sites = {
spotify: /^(spotify:|https:\/\/[a-z]+\.spotify\.com\/)/,
youtube: /^(?:https?:\/\/)?(?:www\.)?(?:youtu\.be\/|youtube\.com\/(?:embed\/|v\/|watch\?v=|watch\?.+&v=))((\w|-){11})(?:\S+)?$/,
};
function validateUrl (url) {
for (var site in sites) {
if ( url.match(sites[site]) ) return site;
}
};
// I/O:
var div = document.querySelector('div');
var input = document.querySelector('input');
input.oninput = reportValidation;
function reportValidation() {
div.textContent = validateUrl(input.value) || 'invalid url';
}
reportValidation();
Type URL:<br>
<input type="text" size="60" value="https://open.spotify.com/track/3JiockjOTd8m2VGcTGkmew">
<div></div>
If you don't need separate returns that depend on Spotify versus YouTube, then you can just combine the regular expressions with |, and forget about the String prototype function:
function validateUrl(url) {
if (url.match(/^(spotify:|https:\/\/[a-z]+\.spotify\.com\/)|^(?:https?:\/\/)?(?:www\.)?(?:youtu\.be\/|youtube\.com\/(?:embed\/|v\/|watch\?v=|watch\?.+&v=))((\w|-){11})(?:\S+)?$/)) {
alert('valid');
} else {
alert('invalid url');
}
};
validateUrl('https://open.spotify.com/track/3JiockjOTd8m2VGcTGkmew');
If the purpose is to just check the origin of URL then shorter will be to check only for spotify.com or youtu.be or youtube.com.
function validateUrl(url) {
if (url.match(/spotify\.com/)) {
alert('spotify');
} else if (url.match(/youtu\.be|youtube\.com/)) {
alert('youtube');
} else {
alert('invalid url');
}
};
validateUrl('https://open.spotify.com/track/3JiockjOTd8m2VGcTGkmew');

Removing %20 from fullname Aweber

Passing variables from Aweber to wordpress Thank you page - However the name appears as follows:
firstname%20Lastname
code used
<script type="text/javascript">
var formData = function() { var query_string = (location.search) ? ((location.search.indexOf('#') != -1) ? location.search.substring(1, location.search.indexOf('#')) : location.search.substring(1)) : '';
var elements = [];
if(query_string) {
var pairs = query_string.split("&");
for(i in pairs) {
if (typeof pairs[i] == 'string') {
var tmp = pairs[i].split("=");
var queryKey = unescape(tmp[0]);
queryKey = (queryKey.charAt(0) == 'c') ? queryKey.replace(/s/g, "_") : queryKey;
elements[queryKey] = unescape(tmp[1]);
}
}
}
return {
display: function(key) {
if(elements[key]) {
document.write(elements[key]);
}
else {
document.write("<!--If desired, replace everything between these quotes with a default in case there is no data in the query string.-->");
}
}
}
}
(); </script>
then
<script>// <![CDATA[
formData.display('fullname')
// ]]></script>
tried
decodeURI(formData.display("fullname"))
But it doesn't work???
I've searched and searched and cant figure it out - Please anyone help???
Thanks.
Im guessing its part of a Wordpress plugin, so you just want a fix right :)
Try replacing this part:
return {
display: function(key) {
if(elements[key]) {
document.write(elements[key]);
} else {
document.write("<!--If desired, replace everything between these quotes with a default in case there is no data in the query string.-->");
}
}
}
With this:
return {
display: function(key) {
if(elements[key]) {
document.write(decodeURIComponent(elements[key]));
} else {
document.write("<!--If desired, replace everything between these quotes with a default in case there is no data in the query string.-->");
}
}
}

how to get data from javascript ajax from another page

I am using a script with jQuery:
$(document).ready(function () {
var button;
var line;
var inputs;
var params = {};
var updatefield;
$('button.update').click(function () {
button = $(this);
params['button'] = button.val();
line = button.closest('.line');
updatefield = line.find('td.resultFromGet');
inputs = line.find('input');
inputs.each(function (id, item) {
switch($(item).attr('type')){
case 'checkbox':{
params[$(item).attr('name')] = new Array($(item).is(':checked'));
break;
}
default:{
params[$(item).attr('name')] = new Array($(item).attr('value'));
break;
}
}
});
//alert(JSON.stringify(params, null, 4));
$.get( 'core/ajax/correct_exec.php', params )
.done(function (data){
if(data == '1'){
$(updatefield).html('UPDATE_RECORD_SUCCESS');
} else {
$(updatefield).html( data );
}
});
});
});
The page I am getting is doing echo '1'; from PHP in case of success.
I try to test this with data == 1 but it doesn't work even though it is a success. In fact, it sends me $(updatefield).html( data ); which is 1. So why can't it just print UPDATE_RECORD_SUCCESS?
The data response is coming with white space, if you use trim() function something like this, then if condition should be executed.
if(data.trim() == '1'){
$('#updatefield').html('UPDATE_RECORD_SUCCESS'); //this should be executed
} else {
$('#updatefield').html( data );
}
Here you can see the space with data in chrome debugger.

Categories

Resources