Uncaught SyntaxError: Unexpected token ) - javascript

I have an html file using which I am rendering a react component.
Here is my html file
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="../../../elements/css/elements.css"/>
<link rel="shortcut icon" href="http://example.com/myicon.ico"/>
</head>
<body>
<h1>Text Modal Demo</h1>
<p>Styled using the Elements SDK.</p>
<br/>
<div id="app"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.3.2/react.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.3.2/react-dom.js"></script>
<script src="https://cdn.polyfill.io/v2/polyfill.js?features=CustomEvent,Intl.~locale.en,Intl.~locale.fr"></script>
<script type="text/javascript" src="../../jsfiles/textModal/dist.text-modal.js"></script>
<script type="text/javascript" src="../../jsfiles/textModal/text-modal.js"></script>
</body>
</html>
And here is my text-modal.js file
function init() {
// Demo eventing API
document.body.dispatchEvent(new CustomEvent('o.InitTextModal', {
detail: { elementId: 'app', contentTemplateLarge: true, footerVisible: true, successBtnCallback: () => { console.log('¡¡success button pressed!!') }}
}
));
}
window.onload = init;
When I try to load the html file, I see this error in my console
Uncaught SyntaxError: Unexpected token ) at Line 5 text-modal.js
which is this line - detail: { elementId: 'app', contentTemplateLarge: true, footerVisible: true, successBtnCallback: () => { console.log('¡¡success button pressed!!') }}
This issue is seen only on IE 11 and Android device. Works fine for iOS

IE11 doesn't support arrow functions. You need to rewrite your javascript:
Before:
() => { console.log('¡¡success button pressed!!') }
After:
function() { console.log('¡¡success button pressed!!') }

Looks like arrow syntax is not supported on IE 11 or some older versions of Android browser.

I haven't tried this much but as far as the error looks this thingy here seems it is not supported better use the same old way of creating functions to make sure it is compatible anywhere
successBtnCallback: () => { // Anything else }
hope that helps

Related

latitude and longitude in node js when a run this code it give an error( Uncaught TypeError: Cannot set properties of null (setting 'textContent')) [duplicate]

This question already has answers here:
How to display JavaScript variables in a HTML page without document.write
(9 answers)
Why does jQuery or a DOM method such as getElementById not find the element?
(6 answers)
Closed 3 months ago.
I want to display latitude and longitude but he some error come :- Here is my code
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<h1>Hello everyone</h1>
<script>
if ('geolocation' in navigator) {
console.log('gelocation is availabe');
navigator.geolocation.getCurrentPosition((position) => {
const lat=position.coords.latitude;
const lon=position.coords.latitude;
document.getElementById('latitude').textContent=lat;
document.getElementById('longitutde').textContent=lon;
// console.log(position);
});
} else {
console.log('geolocation IS NOT available ');
}
</script>
</body>
</html>
I want to display latitude and longitude
You should wait for the DOM to be loaded because before the script in the HTML no element with id longitude neither latiture exist. Encapsulate your if/else code in a document.addEventListener('DOMContentLoaded', () => { ... }) callback.
Then textContent does not exist, use .innerText = ...
<script>
document.addEventListener('DOMContentLoaded', () => {
if ('geolocation' in navigator) {
console.log('gelocation is availabe');
navigator.geolocation.getCurrentPosition((position) => {
const lat=position.coords.latitude;
const lon=position.coords.latitude;
document.getElementById('latitude').innerText = lat;
document.getElementById('longitutde').innerText = lon;
// console.log(position);
});
} else {
console.log('geolocation IS NOT available ');
}
});
</script>

Jsdom load javascript code but doesn't run correctly

What is wrong with this code? It displays the says: hello bar from the out.js console.log but does not run the rest of the script doesn't add the link inside <div id="link"></div>
If I put the script directly in the code it works, but not in a .js file
teste2.js
const jsdom = require("jsdom");
const { JSDOM } = jsdom;
const dom = new JSDOM(`
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<div id="link"></div>
<p>Hello world</p>
<script src="http://localhost/2022/jsdom/out.js"></script>
</body>
</html>`, { resources: "usable", runScripts: "dangerously"});
const document = dom.window.document;
console.log(document.getElementsByTagName('html')[0].innerHTML);
out.js
let T = document.getElementById('link');
T.innerHTML = 'LINK';
console.log('bar says: hello');
JSDOM loads sub-resources asynchronously, so your Node.js code is accessing the DOM before the <script> code has executed.
This is also why the log of document.getElementsByTagName('html')[0].innerHTML appears before the log of 'bar says: hello'.
You can handle this by explicitly waiting for the load event:
const document = dom.window.document;
document.addEventListener('load', () => {
console.log(document.getElementsByTagName('html')[0].innerHTML);
});
You'll need more complex logic if the script itself does anything asynchronously. Firing a custom event that you can listen for is a good approach.

How do I connect an audio worklet to a web page?

I'm trying to connect a web page to an audio worklet (following this demos but I got stuck.
Can somebody help?
Here's the code I've got so far.
Those files are all in the same folder, but they don't log anything.
INDEX.HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<meta name="mobile-web-app-capable" content="yes">
</head>
<body>
<script src="./index.js"></script>
</body>
</html>
INDEX.JS
const demoCode = async () => {
const audioContext = new AudioContext()
await audioContext.audioWorklet.addModule('test-processor.js')
const testNode = new AudioWorkletNode(audioContext, 'test-processor')
testNode.connect(audioContext.destination)
}
TEST-PROCESSOR.JS
class TestProcessor extends AudioWorkletProcessor {
constructor () {
super()
console.log(currentFrame)
console.log(currentTime)
}
process (inputs, outputs, parameters) {
return true
}
}
console.log(sampleRate)
const usefulVariable = 42
console.log(usefulVariable)
registerProcessor('test-processor', TestProcessor)
It looks like you're not invoking your demoCode() function anywhere. If you want to be compliant with the autoplay policy in todays browsers that needs to happen in response to a user gesture.
First you need to add a button to your HTML.
<button id="start" type="button">start</button>
Then you can attach an event listener for that button within your index.js file.
document.getElementById('start').addEventListener('click', demoCode);

Uncaught (in Promise) Error When Using Polyfill for Porting Firefox Extensions to Chrome

I wrote a web extension for Firefox Quantum. The extension has a popup, which when clicked provides a 3 button menu. When one of the buttons is clicked, the extension will inject a DIV containing an iFrame into the user's current page.
Firefox extensions use the promise API and use the browser namespace instead of "callbacks" and the chrome namespace. As such, Mozilla provides a polyfill to allow easy porting of code written for Firefox Extensions.
Excerpt from this article.
If you do write your extension to use browser and promises, then Firefox also provides a polyfill that will enable it to run in Chrome: https://github.com/mozilla/webextension-polyfill.
I followed the tutorial on github to modify the html file for my popup (I removed the CSS classes to make the example more concise):
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<link href="https://fonts.googleapis.com/css?family=Nunito:800" rel="stylesheet">
<script type="application/javascript" src="../polyfills/browser-polyfill.js"></script>
</head>
<body>
<div style="display: flex; flex-direction: column; justify-content: space-evenly; align-items: center; width: 100vw; min-width: 200px;">
<button class="btn" id="3">Short Summary</button>
<button class="btn" id="5">Medium Summary</button>
<button class="btn" id="7">Long Summary</button>
<script src="choose_length_page.js"></script>
</div>
</body>
</html>
Then in my "choose_length_page.js" file, I have the following code:
//Enable the polyfill for the content script and execute it in the current tab
browser.tabs.executeScript({ file: "../polyfills/browser-polyfill.js" }).then(loadContentScript);
function loadContentScript() {
browser.tabs.executeScript({ file: "../inject-content/inject.js" }).then(listenForClicks);
}
function listenForClicks() {
document.addEventListener('click', e => {
if (!e.target.classList.contains('btn')) {
return;
} else {
browser.tabs.query({ active: true, currentWindow: true })
.then(tabs => {
browser.tabs.sendMessage(tabs[0].id, { summaryLength: e.target.id, targetURL: tabs[0].url });
});
}
});
}
However, when I run this code I get the following error ("choose_length_page.html" is the HTML file in this post):
Why is this error happening, and how can I fix it?
Update 1 -
At the suggestion of wOxxOm, I tried to specify paths qualified from the root package. I did this like so:
<head>
<meta charset="utf-8">
<link href="https://fonts.googleapis.com/css?family=Nunito:800" rel="stylesheet">
<script type="application/javascript" src="chrome-extension://__MSG_##extension_id__/polyfills/browser-polyfill.js"></script>
After doing that, I got the following message:
[Deprecation] Subresource requests whose URLs contain embedded credentials (e.g. https://user:pass#host/) are blocked. See https://www.chromestatus.com/feature/5669008342777856 for more details.
So, I don't think that works.
I managed to fix the errors:
I changed my javascript file to (I added catch statements to the promises and I changed the paths to be consistent with JaromandaX's suggestion):
//Enable the polyfill for the content script and execute it in the current tab
browser.tabs.executeScript({ file: "/polyfills/browser-polyfill.js" }).then(loadContentScript).catch((error) => logError(error));
function loadContentScript() {
browser.tabs.executeScript({ file: "/inject-content/inject.js" }).then(listenForClicks).catch((error) => logError(error));
}
function listenForClicks() {
document.addEventListener('click', e => {
if (!e.target.classList.contains('btn')) {
return;
} else {
browser.tabs.query({ active: true, currentWindow: true })
.then(tabs => {
browser.tabs.sendMessage(tabs[0].id, { summaryLength: e.target.id, targetURL: tabs[0].url });
});
}
});
}
function logError(error) {
console.log(error);
}
I also changed the path in the src attribute of the script tag to:
<script type="application/javascript" src="/polyfills/browser-polyfill.js"></script>
The error seemed to be that I did not catch the promises.

Polymer 1.6 and Polymer-cli, access app property from within a custom element

Using the polymer-cli tool, and the shopping cart boilerplate as a starting point, I made a simple mock-up to illustrate the use case.
Assume your index.html file includes "test-app.html" and the matching tag
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, minimum-scale=1.0, initial-scale=1.0, user-scalable=yes">
<title>My App</title>
<link rel="shortcut icon" sizes="32x32" href="/images/app-icon-32.png">
<meta name="theme-color" content="#fff">
<link rel="manifest" href="/manifest.json">
<script>
// setup Polymer options
window.Polymer = {lazyRegister: true, dom: 'shadow'};
// load webcomponents polyfills
(function() {
if ('registerElement' in document
&& 'import' in document.createElement('link')
&& 'content' in document.createElement('template')) {
// browser has web components
} else {
// polyfill web components
var e = document.createElement('script');
e.src = '/bower_components/webcomponentsjs/webcomponents-lite.min.js';
document.head.appendChild(e);
}
})();
// load pre-caching service worker
if ('serviceWorker' in navigator) {
window.addEventListener('load', function() {
navigator.serviceWorker.register('/service-worker.js');
});
}
</script>
<!-- <link rel="import" href="/src/bewi-app.html"> -->
<link rel="import" href="/src/test-app.html">
<style>
body {
margin: 0;
font-family: 'Roboto', 'Noto', sans-serif;
line-height: 1.5;
min-height: 100vh;
background-color: #eee;
}
</style>
</head>
<body>
<span id="browser-sync-binding"></span>
<test-app id="test"></test-app>
</body>
</html>
Now, assume test-app.html containing the following (again a mere simplified copy of my-app.html):
<link rel="import" href="../bower_components/polymer/polymer.html">
<link rel="import" href="../bower_components/app-route/app-location.html">
<link rel="import" href="../bower_components/app-route/app-route.html">
<link rel="import" href="test-element.html">
<dom-module id="test-app">
<template>
<app-location route="{{route}}"></app-location>
<app-route
route="{{route}}"
pattern="/:page"
data="{{routeData}}"
tail="{{subroute}}"></app-route>
test-element is loaded bellow
<test-element></test-element>
<div>
</div>
</template>
<script>
Polymer({
is: 'test-app',
properties: {
page: {
type: String,
reflectToAttribute: true,
observer: '_pageChanged'
},
baseUrl: {
type: String,
value: '/'
},
siteUrl: {
type: String,
value: 'http://fqdn.local'
}
},
observers: [
'_routePageChanged(routeData.page)'
],
_routePageChanged: function(page) {
this.page = page || 'view1';
},
_pageChanged: function(page) {
// load page import on demand.
this.importHref(
this.resolveUrl('my-' + page + '.html'), null, null, true);
}
});
</script>
</dom-module>
Now, the test-element.html
<link rel="import" href="../../bower_components/polymer/polymer.html">
<dom-module id="test-element">
<template>
<div> I am a test </div>
</template>
<script>
(function() {
'use strict';
Polymer({
is: 'test-element',
ready: function() {
console.log('READY');
console.log('find #test using document.querySelector', document.querySelector('#test')); // OK
console.log('find #test .siteUrl using document.querySelector', document.querySelector('#test').siteUrl); // undefined
console.log('find #test .siteUrl using Polymer.dom', Polymer.dom(document.querySelector('#test')).siteUrl); // undefined
console.log('find #test .siteUrl using Polymer.dom().node', Polymer.dom(document.querySelector('#test')).node.siteUrl); // undefined
console.log('find #test .siteUrl using Polymer.dom().properties', Polymer.dom(document.querySelector('#test')).node.properties); // {object} but, I'm guessing not the computed values of the properties
// So, how may I access the #test app's "siteUrl" property from within a custom element?
}
});
})();
</script>
</dom-module>
So, the real question is, how may test-element access the property "siteUrl" in the main app?
I'm planning to make this variable readOnly, and access it from other custom elements.
I'ld prefer this approach VS passing the siteUrl as an attribute to the test-element element..
What do you think?
The right way to pass information through elements is using the Data Binding system, i.e. "passing the siteUrl as an attribute to the test-elemet element"
You'll accomplish the Read Only requirement surrounding the variable with square brackets, like this [[siteUrl]] as described in Property change notification and two-way binding.
You can set a variable in a global environment as you said like
<script>
var myGlobalVar = 'is accessible in any element'
Polymer({
is: 'test-app',
// ...
});
</script>
and you can access it in every element.
BUT, global variables are not recommended as you may know. References about why in the links below.
Global Variables Are Bad
Why are global variables considered bad practice?
I've Heard Global Variables Are Bad, What Alternative Solution Should I Use?

Categories

Resources