React fetch() not working on mobile only - javascript

I'm an intern assisting on developing a simple landing page for our company. The main page is essentially a search bar, and as a user types if their query matches a credit union in our database, the name of that credit union is output below with a link to its page. Imagine a google-esque search bar.
This works great on desktop but for some reason, on mobile when a user types in a query, nothing comes up at all, even if they're typing something that most definitely exists in our database.
To see the site in action, it's http://mycuapp.com .
Here is the relevant HTML:
<Search></Search>
<div id = "results-bar" class="hidden"></div>
and the JS:
handleTyping(event) {
event.preventDefault();
event.stopPropagation();
const data = new FormData(event.target);
var query = event.target.value;
var url = "/search/" + query;
var i;
if (query.length >= 3) {
fetch(url, {
method: "GET",
}).then((value) => {
return value.json();
}).then((Response)=>{
var item = document.getElementById("results-bar");
if(item.className=='hidden'){
item.className = 'unhidden' ;
clickedButton.value = 'hide';
}
for (i = 0; i < Response.payload.length; i++){
var displayName = Response.payload[i].displayName;
var cuURL = Response.payload[i].url;
if(document.getElementById("results-bar").innerHTML.indexOf(displayName) == -1){ //not yet displayed in search results
var result = "<div class = 'result'><a href='" + cuURL + "'><p>" + displayName + "</p></a></div>";
document.getElementById("results-bar").innerHTML += result;
}
console.log(Response.payload[i].displayName);
}
});
}
}
render() {
return (
<form className="" id="search-form">
<input onKeyUp={this.handleTyping} type="text" autoComplete="off" name="query" placeholder="Search your credit union's name to download the mobile banking app."/>
</form>
);
}
Any insight would be greatly appreciated, including any suggestions on how to debug the problem from an iPhone (bc when simulated with Chrome's developer tools there is no issue).
EDIT: Turns out the problem is the line "const data = new FormData(event.target);" FormData is incompatible with Safari, or something. Our lead programmer caught it. Once we got rid of that line everything works great! Thanks everyone for your help.

Seems like you are trying to use Response stream which is not fully supported on Mobile Safari.
https://developer.mozilla.org/en-US/docs/Web/API/Response
Alternatively you can use fetch polyfill which is supported in Safari 6.1+
https://github.com/github/fetch
FormData: https://developer.mozilla.org/en-US/docs/Web/API/FormData
Is not compatible with Safari Mobile.

Related

JavaScript function being blocked by office addin

I have an outlook add-in that I have created. In this add-in I am trying to make a button pull some data from a website using APIs.
I was able to do this on with a local test but when I put the code into my add-in nothing happens. It gives an error in the console that says Tracking Prevention blocked access to storage for https://appsforoffice.microsoft.com/lib/1/hosted/en-us/outlook_strings.js. but when I commented out my javascript code, that error still came up. So I don't know why my code is being blocked.
Picture of problem:
On my local computer it works no problem:
Here is my code:
javascript:
function freshdesktickets() {
Office.onReady((info) => {
// window.parent.location.reload()
const url = "https://alloysystems.freshdesk.com/api/v2/tickets";
fetch(url, {
method: "GET",
withCredentials: true,
headers: {
// needed to base64 encode my key with ":x" at the end of the api key then I used that for the authorization header.
"authorization": "Basic YOUWILLNEVERGETMYAPIKEYLOL"
}
})
.then(resp => resp.json())
.then(data => {let text = "";
const output = document.querySelector('span.ms-font-m');
for (let i = 0; i < data.length; i++) {
let text = "Subject: " + JSON.stringify(data[i].subject) + "<br>"+
"CC Emails: " + JSON.stringify(data[i].cc_emails).replace("[]","No Emails are CC'd").replace("[","").replace("]","") + "<br>" +
"Ticket Creation Date: " + JSON.stringify(data[i].created_at) + "<br>" +
"Ticket Status: " + JSON.stringify(data[i].status).replace("2", "Open").replace("3", "Pending").replace("4", "Resolved").replace("5", "Closed").replace("6", "Waiting On Customer") ;
let pre = document.createElement('pre');
pre.innerHTML = text;
pre.style.cssText += 'font-size:24px;font-weight:bold;'
output.appendChild(pre);
console.log(pre)
}
})})
}
HTML:
<div class="ms-PanelExample">
<script src="https://static2.sharepointonline.com/files/fabric/office-ui-fabric-js/1.4.0/js/fabric.min.js"></script>
<button style="margin:1px;" id="get-freshdesk" class="ms-Button ms-Button--primary">
<span class="ms-Button-label">Freshdesk Tickets</span>
</button>
<div class="ms-Panel ms-Panel--xxl">
<button class="ms-Panel-closeButton ms-PanelAction-close">
<i class="ms-Panel-closeIcon ms-Icon ms-Icon--Cancel"></i>
</button>
<div class="ms-Panel-contentInner">
<p class="ms-Panel-headerText">Freshdesk Integration</p>
<div class="ms-Panel-content">
<span class="ms-font-m">Latest Ticket information</span>
</div>
</div>
</div>
</div>
<script type="text/javascript">
var PanelExamples = document.getElementsByClassName("ms-PanelExample");
for (var i = 0; i < PanelExamples.length; i++) {
(function() {
var PanelExampleButton = PanelExamples[i].querySelector(".ms-Button");
var PanelExamplePanel = PanelExamples[i].querySelector(".ms-Panel");
PanelExampleButton.addEventListener("click", function(i) {
new fabric['Panel'](PanelExamplePanel);
});
}());
}
</script>
Result from console:
Tracking Prevention blocked access to storage for https://appsforoffice.microsoft.com/lib/1/hosted/en-us/outlook_strings.js.
### yet it displays the pre information in the console below because I added console.log(pre)
I also tried adding the domains of where the api gets its data but I am still getting the error. I added it to the edge's exclusion list and I also added it to the manifest xml.
code that was added to the manifest xml to ensure that the api's domain is allow to get some data:
<!-- Domains that will be allowed when navigating. For example, if you use ShowTaskpane and then have an href link, navigation will only be allowed if the domain is on this list. -->
<AppDomains>
<AppDomain>https://freshdesk.com</AppDomain>
<AppDomain>https://alloysystems.freshdesk.com</AppDomain>
<AppDomain>AppDomain3</AppDomain>
</AppDomains>
<!--End Basic Settings. -->
I think I figured out the answer. The problem is that I added the javascript to my existing office apps javascript which has Office.onReady((info) => at the top of the script. If I add my javascript to the existing office apps javascript it will fail.
So I made a new javascript file and added that to the html. In the new file I used the javascript code above, then I simply added the script to the head tag and it started working.

mailto client does not work in mobile devices and blocks the popup

I am trying to add a mailto button to send an email using email client
Here is my code:
clickEmail(e) {
let storyId = this.refs.storyToEmail.getAttribute('id');
if (storyId != undefined) {
let urlToSend = this.createURL(storyId) + "?ref=emailShare";
let subjectLine = "Shared story - " + this.props.headline;
let hrefValue = "mailto:?subject=".concat(subjectLine, "&body=", "I thought you might find this interesting:%0D%0A %0D%0A", urlToSend, "%0D%0A %0D%0AConnecting Communitie %0D%0A %0D%0A");
let email = this.refs.storyToEmail;
email.href = hrefValue;
return email.href;
}
}
However this works for me and almost all desktops and not working on many mobile devices.
After searching I noticed it needs permission from the browser as follows:
https://blog.hubspot.com/marketing/set-gmail-as-browser-default-email-client-ht
But the issue is I cannot find anyway to do the setting as suggested in the link for mobile(chrome)?
Can anyone shed light on this?

Display summary of choices in JS

this is my first time here as a poster, please be gentle! I have zero knowledge of JS (yet, working on it) but am required to do some JS anyway. Here's my problem. I got some code (not mine) allowing a user to select multiple choices. I found the function that gathers these choices and store them
function getProductAttribute()
{
// get product attribute id
product_attribute_id = $('#idCombination').val();
product_id = $('#product_page_product_id').val();
// get every attributes values
request = '';
//create a temporary 'tab_attributes' array containing the choices of the customer
var tab_attributes = [];
$('#attributes select, #attributes input[type=hidden], #attributes input[type=radio]:checked').each(function(){
tab_attributes.push($(this).val());
});
// build new request
for (var i in attributesCombinations)
for (var a in tab_attributes)
if (attributesCombinations[i]['id_attribute'] === tab_attributes[a])
request += '/'+attributesCombinations[i]['group'] + '-' + attributesCombinations[i]['attribute'];
$('#[attsummary]').html($('#[attsummary]').html() + attributesCombinations[i]['group']+': '+attributesCombinations[i]['attribute']+'<br/>')// DISPLAY ATTRIBUTES SUMMARY
request = request.replace(request.substring(0, 1), '#/');
url = window.location + '';
// redirection
if (url.indexOf('#') != -1)
url = url.substring(0, url.indexOf('#'));
// set ipa to the customization form
$('#customizationForm').attr('action', $('#customizationForm').attr('action') + request);
window.location = url + request;
}
I need to make a simple display summary of these choices. After quite a bit of searching and findling, I came with the line with the DISPLAY SUMMARY comment, this one:
$('#[attsummary]').html($('#[attsummary]').html() + attributesCombinations[i]['group']+': '+attributesCombinations[i]['attribute']+'<br/>')
In the page where I want those options, I added an empty div with the same ID (attsummary):
<div id="attsummary"></div>
Obviously, it is not working. I know I don't know JS, but naively I really thought this would do the trick. May you share with me some pointers as to where I went wrong?
Thank you very much.
Correct form of the line it isn't working for you:
$('#attsummary').html($('#attsummary').html() + attributesCombinations[i]['group']+': '+attributesCombinations[i]['attribute']+'<br/>')

Email Client in Android using phonegap

I am tryin to use an email client in my application. I am using plugins for the same.
The code that am using is
function tellAFriend()
{
var succcallback = function(result) {
//alert("Mail sent");
};
var errorcallback = function(e) {
//alert("error:" + e);
};
var body1='Hi,\n I came across this new app and thought you might be interested';
var body2=body1+'.You can check it out at \n';
var href1='market';
var anchortext;
anchor1 = document.createElement("a");
anchortext = document.createTextNode('Test');
anchor1.appendChild(anchortext);
anchor1.href=href1;
anchor1.setAttribute('href','https://market.android.com/details?id=com.unisys.cps&feature=search_result#?t=W251bGwsMSwxLDEsImNvbS51bmlzeXMuY3BzIl0');
//alert(anchor1);
window.plugins.webintent.tellAFriend({
mailSubject : 'CPS Mobile App',
mailRecepients: '',
mailBody: href1
//mailBody: 'Hi,\n I came across this new app and thought you might be interested.You can check it out at \nhttps://market.android.com/details?id=com.unisys.cps&feature=search_result#?t=W251bGwsMSwxLDEsImNvbS51bmlzeXMuY3BzIl0 \nor \nhttps://www.cargoportalservices.com/lmsweb/DownloadCPSMobileApp.jsp'
}, succcallback, errorcallback);
}
Thats the function. In the function, the mail body that i have provided needs to be a text. but I need to pass a hyoerlink to it. Meaning, when the email client opens up, the text should be displayed as hyperlinks.
Any suggestions on how that can be achieved.

Query String for pre-filling html form field

I manage a website for an organization that has separate chapter sites. There is a membership signup form that is on the main website that each chapter links to. On the form there is a dropdown box that allows a person to choose the chapter they want to join. What I would like to do is have each chapter website use a specific link to the form that will preselect their chapter from the dropdown box.
After searching the web, I found that I will probably need to use a Javascript function to utilize a Query String. With all my searching, I still can't figure out the exact code to use. The page is a basic HTML page...no php and it is hosted on a linux server.
Any help would be greatly appreciated.
If you format your url like this:
www.myorg.com?chapter=1
You could add this script to your html head:
function getparam(name) {
name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
var regexS = "[\\?&]" + name + "=([^&#]*)";
var regex = new RegExp(regexS);
var results = regex.exec(window.location.href);
if (results == null)
return "";
else
return results[1];
}
function loadform()
{
var list = document.getElementById("mychapterdropdown");
var chapter = getparam("chapter");
if (chapter>=0 && chapter < list.options.length)
{
list.selectedIndex = chapter;
}
}
The in your html body tag:
<body onload="loadform();" >
Could probably add more validation checks but that's the general idea.
It sounds like what you are looking for are GET or POST requests. For instance, if your user selects "Chapter A" from your form and hits select, you can allow redirects from another site (for instance http://www.yoursite.com/form.html?chapter=A) to allow Chapter A to be preselected. In Javascript this is done by
var chapter="";
var queryString = location.search.substring(1);
if ( queryString.length > 0 ) {
var getdata = queryString.split("&");
var keyvalues;
for(var i=0; i < getdata.length; i++){
keyvalues = getdata.split("=");
}
} else {
chapter = "Not Found";
}
document.getElementById( "ChapterID").value = keyvalues['chapter'];
This is untested, so don't hold me to it :).
maybe something using parse_url
$params = parse_url()
$query = $params['query'];
$query_pairs = explode('&',$query);
$key_val = array();
foreach($query_pairs as $key => $val){
$key_val[$key] = $val;
}
http://www.php.net/manual/en/function.parse-url.php
You would probably have to use an dynamic ajax content. Use the following javascript to read the querystring, then load the html file in that div using this javascript.

Categories