I am trying to import https://github.com/tkurki/dnssd.js and make html file like this:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1">
<script src="/index.js"></script>
</head>
<body>
<section>
<h1>DNS-SD Browser</h1>
<div id="services"></div>
</section>
<script>
const dnssd = require('dnssd2');
// advertise a http server on port 4321
const ad = new dnssd2.Advertisement(dnssd.tcp('http'), 4321);
ad.start();
// find all chromecasts
const browser = dnssd2.Browser(dnssd.tcp('_http'))
.on('serviceUp', service => console.log("Device up: ", service))
.on('serviceDown', service => console.log("Device down: ", service))
.start();
</script>
</body>
</html>
But somehow it shows me error in console log:
Uncaught ReferenceError: require is not defined at index.js:1
Uncaught ReferenceError: require is not defined at index.js:18
What am I doing wrong please?
index.js contains:
var Advertisement = require('./lib/Advertisement');
var Browser = require('./lib/Browser');
var ServiceType = require('./lib/ServiceType');
var validate = require('./lib/validate');
var resolve = require('./lib/resolve');
var NetworkInterface = require('./lib/NetworkInterface');
module.exports = {
Advertisement: Advertisement,
Browser: Browser,
ServiceType: ServiceType,
tcp: ServiceType.tcp,
udp: ServiceType.udp,
all: ServiceType.all,
validate: validate,
resolve: resolve.resolve,
resolveA: resolve.resolveA,
resolveAAAA: resolve.resolveAAAA,
resolveSRV: resolve.resolveSRV,
resolveTXT: resolve.resolveTXT,
resolveService: resolve.resolveService,
};
The browser doesn't support require function
Use requirejs. You can also use it with jquery
You can learn about requirejs from here
Browser doesn't support require out-of-box. try adding this script tag to manually import require from its cdn.
<script src="https://cdnjs.cloudflare.com/ajax/libs/require.js/2.3.6/require.js"></script>
<script src="/index.js"></script>
Related
I want to test the new Firefox Storage Access API to allow 1st party storage (cookie, local storage, indexeddb, ...) to an iframe of a different domain (but still under my control).
Parent Markup / code
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Parent Domain</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/js-cookie/2.2.0/js.cookie.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jschannel/1.0.0-git-commit1-8c4f7eb/jschannel.min.js"></script>
</head>
<body>
<div>
Cookies: <ul class="cookie-data"></ul>
</div>
<iframe
id="rpc-gateway"
src="http://child.local:8080/iframe-firefox.html"
sandbox="allow-storage-access-by-user-activation allow-scripts allow-same-origin"></iframe>
<script type="text/javascript">
var chan = Channel.build({
window: document.getElementById("rpc-gateway").contentWindow,
origin: "*",
scope: "testScope"
});
</script>
</body>
</html>
Child Iframe Markup / code
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Child Domain</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/js-cookie/2.2.0/js.cookie.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jschannel/1.0.0-git-commit1-8c4f7eb/jschannel.min.js"></script>
</head>
<body>
<button onClick="onLoginClick()">Login</button>
<script type="text/javascript">
var chan = Channel.build({
window: window.parent,
origin: "*",
scope: "testScope"
});
let onLoginClick = function(trans, params) {
document.hasStorageAccess().then(hasAccess => {
if (!hasAccess) {
console.log("no access - requesting access");
return document.requestStorageAccess();
}
}).then(_ => {
document.hasStorageAccess().then(hasAccess => {
console.log("hasAccess:", hasAccess);
window.localStorage.setItem('foo', 'bar');
})
}).catch((err) => {
console.log("hasStorageAccess() failed", err);
});
};
</script>
</body>
</html>
When clicking on the "Login" button from the Child Iframe, the following log output is generated:
no access - requesting access # iframe-firefox.html:22:25
hasAccess: true # iframe-firefox.html:27:25
Request to access cookie or storage on “http://child.local:8080/iframe-firefox.html” was blocked because we are blocking all third-party storage access requests and content blocking is enabled. # iframe-firefox.html:28:24
The visible conclusion is:
The promise document.hasStorageAccess() resolves
The hasAccess parameter is initially 'false'
The promise of document.requestStorageAccess() is returned and resolves
The 2nd promise document.hasStorageAccess() resolves
The hasAccess parameter is now 'true'
nevertheless, simple storage access to local storage is not possible.
What do I do wrong?
More Info's:
Firefox Developer Edition Version 65.0b9
Content Blocking Setting:
This seems to be a bug in the version of Firefox you're using. I set up a test locally of what you have and in Firefox 69.0.1 (64 bit), I get no error and the value is stored to local storage. When I took the sandbox flag allow-storage-access-by-user-activation out of the parent iframe, the child failed to get permission for local storage, so that confirms that my setup was actually working properly. Here's what I did:
Created a Node.js/Express server for the parent:
const express = require('express');
const cors = require('cors');
const path = require('path');
const server = express();
server.use(cors());
server.use(express.static(path.resolve('./public')));
server.listen(8080, function() {
console.log('listening on *:8080');
});
Created a Node.js/Express server for the child (with different port to trigger same origin policy):
const express = require('express');
const cors = require('cors');
const path = require('path');
const server = express();
server.use(cors());
server.use(express.static(path.resolve('./public')));
server.listen(8081, function() {
console.log('listening on *:8081');
});
Created an index.html for the parent (pretty much the same as yours):
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Parent Domain</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/js-cookie/2.2.0/js.cookie.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jschannel/1.0.0-git-commit1-8c4f7eb/jschannel.min.js"></script>
</head>
<body>
<div>
Cookies: <ul class="cookie-data"></ul>
</div>
<iframe
id="rpc-gateway"
src="http://127.0.0.1:8081/iframe-firefox.html"
sandbox="allow-storage-access-by-user-activation allow-scripts allow-same-origin"></iframe>
<script type="text/javascript">
var chan = Channel.build({
window: document.getElementById("rpc-gateway").contentWindow,
origin: "*",
scope: "testScope"
});
// Added this to try out the JSChannel
chan.call({
method: "reverse",
params: "hello world!",
success: function(v) {
console.log(v);
}
});
</script>
</body>
</html>
And created iframe-firefox.html for the child:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Child Domain</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/js-cookie/2.2.0/js.cookie.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jschannel/1.0.0-git-commit1-8c4f7eb/jschannel.min.js"></script>
</head>
<body>
<button onClick="onLoginClick()">Login</button>
<script type="text/javascript">
var chan = Channel.build({
window: window.parent,
origin: "*",
scope: "testScope"
});
// Other end of the JSChannel call
chan.bind("reverse", function(trans, s) {
return s.split("").reverse().join("");
});
let onLoginClick = function(trans, params) {
document.hasStorageAccess().then(hasAccess => {
if (!hasAccess) {
console.log("no access - requesting access");
return document.requestStorageAccess();
}
}).then(_ => {
document.hasStorageAccess().then(hasAccess => {
console.log("hasAccess:", hasAccess);
window.localStorage.setItem('foo', 'bar');
})
}).catch((err) => {
console.log("hasStorageAccess() failed", err);
});
};
</script>
</body>
</html>
And everything worked as expected... So I'm feeling pretty sure that the issue is with the specific version of Firefox Developer Edition that you're using.
Also, here's a link to a zip of my setup if you want to give it a try on your end and see if this works differently than what you have: server.zip
Let me know if there's anything else I can do to help.
Here is my code :
// And my javascript file verbatims.js :
class Verbatims {
list() {
return ["c'est super", "j'aime pas", "ça marche bien"];
}
}
module.exports = Verbatims;
<!DOCTYPE html>
<html lang="fr">
<head>
<meta charset="utf-8">
<meta content="X-Content-Type-Options: nosniff">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/1.0.18/vue.min.js"></script>
<script src="/src/verbatims.js" type="application/javascript"></script>
<title>My Project</title>
</head>
<body>
<div id="PRISME_data">
Le nombre de requête est de : {{ nb_request }}<br>
<button v-on:click="change">Change value</button>
<button v-on:click="stop">Arrêter</button>
</div>
<script>
let app = new Vue({
el:'#PRISME_data',
data: {
nb_request: "toto",
ite: 0
},
methods: {
change: function() {
changeNbRequest()
},
stop: function() {
clearInterval()
}
}
});
changeNbRequest = function() {
var timer = setInterval(function() {
let verbatim = new Verbatims().list()[ite];
}, 5000);
}
</script>
</body>
</html>
When I try to display my page with my node server I have this error :
Uncaught ReferenceError: Verbatims is not defined at index:45
on this line : let verbatim = new Verbatims().list()[ite];
I don't see why, I have try a lot of things but nothing work ! Do you have any idea ?
Thank you :)
This might be happening because of the following:
The verbatims.js file is not loading in the browser because of
wrong path.
The verbatims.js file that reached the browser does
not contain your class.
You did not import the Verbatims class on the referencing script.
Fix for 3rd option should be like this:
<script type="module">
import {Verbatims} from './src/vebatim.js';
....ommitted for brevity
changeNbRequest = function() {
var timer = setInterval(function() {
let verbatim = new Verbatims().list()[ite];
}, 5000);
}
</script>
Additional TIP
To improve your code, try to place all the JS code inside your index.html to an external file so you can take advantage of ES6 import/export features.
I'm trying to load two scripts that were functionally deferred on account of their type attributes being non-standard i.e. text/javascript/defer. Doing this causes the parser to ignore them so I want to reload them using JavaScript.
My HTML is as below:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<title>No Title</title>
<meta name="keywords" content="">
<meta name="description" content="">
<meta name="viewport" content="width=device-width, initial-scale=1">
<script type="text/javascript/defer" src="assets/js/test3.js"></script>
<script type="text/javascript/defer" src="assets/js/test4.js"></script>
<script type="text/javascript" src="assets/js/jquery.js"></script>
<script>
$(document).ready(function(){
var defer_js_collection_obj = $("[type='text/javascript/defer']"),
el_head_rq_obj = $('head'),
el_head_obj = el_head_rq_obj[0]
;
if(defer_js_collection_obj.length > 0)
{
//Reload JavaScript
defer_js_collection_obj.each(function() {
var file_src_outer_html_str = this.outerHTML;
var file_src_res_arr = file_src_outer_html_str.match("src *\= *[\"\']{1}(.*?)[\"\']{1}");
var file_src_str = file_src_res_arr[1];
var fileref = document.createElement('script');
fileref.setAttribute("type", "text/javascript");
fileref.setAttribute("src", file_src_str);
document.getElementsByTagName("head")[0].appendChild(fileref);
});
//Unload JavaScript with defer tag
for(var j = defer_js_collection_obj.length-1; j >= 0; j--)
{
defer_js_collection_obj[j].parentNode.removeChild(defer_js_collection_obj[j]);
}
}
});
</script>
</head>
<body>
<div>Load Deferred JavaScript</div>
</body>
</html>
jquery.js is version 1.11.2. test3.js and test4.js reference the javascript files I want to load, and they contain console.log('test3.js is loaded'); and console.log('test4.js is loaded'); respectively.
The issue I'm having is that this script works virtually everywhere else except on Firefox. I'm on a Mac OS X 10.10.5 using Firefox 46.0.1, and I don't see the console.log message when I load the script.
How can I fix this?
It might be a mime type issue. Do you happen to see any message in the console stating "not well-formed"? In any case, this seemed to work for me and I agree that your code did not work in FF when I first tried it.
$(document).ready(function(){
console.log("main");
var $body = $($("body")[0]);
var $scripts = $("[type='text/javascript/defer']");
$scripts.each(function(){
var scriptTag = document.createElement("script");
scriptTag.setAttribute("type", "text/javascript");
scriptTag.setAttribute("src", $(this).attr("src"));
$body.append(scriptTag);
});
});
Try to append your script at the end of body, so instead do:
document.getElementsByTagName("body")[0].appendChild(fileref);
I have a lot of HTML documents in the root of my projects. Let's take a simple skeleton HTML document like so:
<!doctype html>
<html class="no-js" lang="">
<head>
<meta charset="utf-8">
<meta http-equiv="x-ua-compatible" content="ie=edge">
<title></title>
<meta name="description" content="">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="shortcut icon" type="image/x-icon" href="favicon.ico">
<!-- Place favicon.ico in the root directory -->
<link rel="stylesheet" href="css/style.css">
</head>
<body>
<!--[if lt IE 8]>
<p class="browserupgrade">You are using an <strong>outdated</strong> browser. Please upgrade your browser to improve your experience.</p>
<![endif]-->
hello
hello
hello
hello
hello
<script src="http://code.jquery.com/jquery-1.11.3.min.js"></script>
<script src="js/scripts.js"></script>
</body>
</html>
Now before I send all these files to the development team, I am assigned with the task of checking that there are no links which have no href, and empty href, or have an empty fragment as an href. I.e.,
Basically, there cannot be likes like so:
<a href="">
or
<a href="#">
or
<a>
I found this gulp plugin and but I have a few issues with it. Let's have a look at the gulp file first:
gulp.task("checkDev", function(callback) {
var options = {
pageUrls: [
'http://localhost:8080/Gulp-Test/index.html'
],
checkLinks: true,
summary: true
};
checkPages(console, options, callback);
});
Note that when you pass the option checkLinks: true , it's not just for the a tags , it for all of the tags mentioned on this page. The plugin doesn't have a problem if the <a> tag is empty or just has a # or is not present at all.
See what happens when I run the gulp tasks:
So what I would like instead is, if only the a links could be checked and if the <a> tag doesn't have an href or a blank value or just a #, then it should throw an error or show it in the summary report.
Lastly, see in the sample of the gulp file how I am passing the pageUrl (i.e. the pages to be checked basically) like so:
pageUrls: [
'http://localhost:8080/Gulp-Test/index.html'
],
How do I instead tell this plugin to check for all the .html files inside the Gulp-Test directory ?
So to summarize my question: how do I get this plugin to throw an error (i.e. show in the summary report) when it sees an <a> without a href or a href that is blank or has a value of # and also how do I tell this plugin to check for all .html files inside a directory.
I am assigned with the task of checking that there are no links which have no href, and empty href, or have an empty fragment as an href.
If that's all you require, you don't really need any gulp plugins. And it's doubtful that you will find something that fits your specific requirements anyway.
You can accomplish this yourself pretty easily however. All you really have to do is:
Read in all the HTML files you want to validate using gulp.src().
Pipe each file to a function of your own using through2.
Parse each file using any HTML parser you like (e.g. cheerio).
Find the bad links in the parsed HTML DOM.
Log the bad links using gutil.log() so you will know what to fix.
Maybe throw a gutil.PluginError so your build fails (this is optional).
Here's a Gulpfile that does exactly that (referencing the above points in comments):
var gulp = require('gulp');
var through = require('through2').obj;
var cheerio = require('cheerio');
var gutil = require('gulp-util');
var path = require('path');
var checkLinks = function() {
return through(function(file, enc, cb) { // [2]
var badLinks = [];
var $ = cheerio.load(file.contents.toString()); // [3]
$('a').each(function() {
var $a = $(this);
if (!$a.attr('href') || $a.attr('href') == '#') { // [4]
badLinks.push($.html($a));
}
});
if (badLinks.length > 0) {
var filePath = path.relative(file.cwd, file.path);
badLinks.forEach(function(badLink) {
gutil.log(gutil.colors.red(filePath + ': ' + badLink)); // [5]
});
throw new gutil.PluginError( 'checkLinks',
badLinks.length + ' bad links in ' + filePath); // [6]
}
cb();
});
}
gulp.task('checkLinks', function() {
gulp.src('Gulp-Test/**/*.html') // [1]
.pipe(checkLinks());
});
Running gulp checkLinks with a Gulp-Test/index.html like so ...
<html>
<head><title>Test</title></head>
<body>
<a>no href</a>
empty href
empty fragment
non-empty fragment
link
</body>
</html>
... results in the following output:
[20:01:08] Using gulpfile ~/example/gulpfile.js
[20:01:08] Starting 'checkLinks'...
[20:01:08] Finished 'checkLinks' after 21 ms
[20:01:08] Gulp-Test/index.html: <a>no href</a>
[20:01:08] Gulp-Test/index.html: empty href
[20:01:08] Gulp-Test/index.html: empty fragment
/home/sven/example/gulpfile.js:22
throw new gutil.PluginError( 'checkLinks',
^
Error: 3 bad links in Gulp-Test/index.html
var gulp = require('gulp');
var jsdom= require('jsdom').jsdom;
var fs=require('fs');
var colors= require('colors');
colors.setTheme({
error:"red",
file:"blue",
info:"green",
warn:"yellow"
});
gulp.task('checkLinks',function() {
fs.readdir('.',function(err, files){
if(err)
throw err;
var htmlFiles=files.filter(function(c,i,a){
return c.substring(c.lastIndexOf('.')+1)==="html";
});
htmlFiles.forEach(function(c,i,a){
fs.readFile(c,function(fileReadErr,data){
if(fileReadErr)
throw fileReadErr;
var doc= jsdom(data);
var window= doc.defaultView;
var $=require('jquery')(window);
var aTags=$('a').toArray();
var k=0;
console.log(("\n\n************************Checking File "+c+"***************************").info);
for(var i=0; i<aTags.length; i++){
if(!(aTags[i].hasAttribute("href")) || aTags[i].getAttribute("href")==="" || aTags[i].getAttribute("href")==="#" ) {
k++;
console.log("BAD LINK ".error+aTags[i].outerHTML.info+" IN FILE "+c.file);
}
}
console.log(("BAD-LINKS COUNT IN " +c+" is "+k).bgRed.white);
window.close();
});
});
});
});
output:
I am using Arcgis Javascript API. API is built on dojo toolkit. So I need to use dojo features in API. I am preparing dojo config file as following.
var pathRegex = new RegExp("/\/[^\/]+$/");
var locationPath = location.pathname.replace(pathRegex, '');
var dojoConfig = {
async: true,
parseOnLoad: false,
baseUrl:"js/",
packages: [
{
name: "application",
location: locationPath + '/js/application'
}]
};
I created a bootstrapper.js like following.
require(["application/main", "dojo/domReady!"], function (application) {
console.log("bootstrapper is running");
application.Run();
})
And index.html file is like this.
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Arcgis Javacsript API Samples</title>
<link rel="stylesheet" href="http://serverapi.arcgisonline.com/jsapi/arcgis/3.5/js/dojo/dijit/themes/claro/claro.css">
<link rel="stylesheet" href="http://serverapi.arcgisonline.com/jsapi/arcgis/3.5/js/esri/css/esri.css">
</head>
<body class="claro">
<div id="map"></div>
<script src="//js.arcgis.com/3.6/"></script>
<script src="js/application/djConfig.js"></script>
<script src="js/application/bootstrapper.js"></script>
</body>
</html>
My application is hosted on IIS and has addres like this htp://domain/Demo/Sample1/index.html
when I run application, this code giving error like following.
"NetworkError: 404 Not Found - http://js.arcgis.com/3.6/js/dojo/application/main.js"
If I set bootstrapper.js file as following, problem is solwing.
require(["js/application/main.js", "dojo/domReady!"], function (application) {
console.log("bootstrapper is running");
application.Run();
})
Try to change your script order in index.html file. Your config settings should load before CDN.
<div id="map"></div>
<script src="js/application/djConfig.js"></script>
<script src="//js.arcgis.com/3.6/"></script>
<script src="js/application/bootstrapper.js"></script>
</body>