Cannot Get Typeahead.js Working with MVC 5 Over Remote - asp.net-mvc-5

I have no idea what I'm doing wrong, but I cannot get typeahead working in my MVC 5 application. I installed everything via NuGet and my view includes #Scripts.Render("~/bundles/typeahead"), which is rendering properly when viewing the source of the view. So the issue isn't that the dependencies are missing.
I am not seeing any drop down appear when I start typing, and using Fiddler I do not see any calls being made out to the remote that I setup that pulls the data.
Here's the line in my view that typeahead is being attached:
#Html.TextBoxFor(m => m.MainInfo.CompanyName,
new { #class = "form-control typeahead", id = "comp-name", autocomplete="off" })
Here's the portion of my script that configures typeahead and bloodhound:
$(document).ready(function() {
var clients = new Bloodhound({
datumTokenizer: function (datum) {
return Bloodhound.tokenizers.whitespace(datum.value);
},
queryTokenizer: Bloodhound.tokenizers.whitespace,
remote: {
url: "/info/client?like=%QUERY",
wildcard: '%QUERY',
filter: function (clients) {
return $.map(clients, function (client) {
return {
value: client.Name,
clientId: client.Identifier
};
});
}
}
});
clients.initialize();
$('#comp-name').typeahead(null,
{
display: 'value',
minLength: 1,
source: clients.ttAdapter(),
templates: {
empty: "Looks like a new client...",
suggestion: Handlebars.compile("<p><b>{{value}}</b> - {{clientId}}</p>")
}
});
});
Is there something that I've configured wrong in my javascript? I've used a few tutorials as well as their own documentation, but I cannot figure out what I'm doing wrong here. It almost feels like it's not properly initialized, but there are no errors being thrown.
NOTE: Just as an FYI I'm using Bootstrap 3 as well in case that changes anything.
EDIT: Here's my #section Scripts:
#Scripts.Render("~/bundles/jqueryval")
#Scripts.Render("~/bundles/typeahead")
<script src="#Url.Content("~/Scripts/handlebars.min.js")"></script>
<script src="#Url.Content("~/Scripts/ProjectSetupFormScripts.js")"></script> <-- this is where typeahead is set up

This did the trick for me:
JS
#section Scripts {
<script type="text/javascript">
$(function () {
SetupTipeahead();
});
function SetupTipeahead() {
var engine = new Bloodhound({
remote: {
url: '/Employees/AllEmployees',
ajax: {
type: 'GET'
}
},
datumTokenizer: function (d) {
return Bloodhound.tokenizers.whitespace(d.FullName);
},
queryTokenizer: Bloodhound.tokenizers.whitespace
});
engine.initialize();
$('#FullName').typeahead(null, {
displayKey: 'FullName',
source: engine.ttAdapter(),
templates: {
empty: [
'<div class="empty-message">',
'No match',
'</div>'
].join('\n'),
suggestion: function (data) {
return '<p class="">' + data.FullName + '</p><p class="">' + data.ManNumber + '</p>';
}
}
});
}
</script>
EmployeesController has the following JsonResult
public JsonResult AllEmployees()
{
return Json(db.Employees.ToList(),JsonRequestBehavior.AllowGet);
}

Hello try to wrap your script in #section scripts {} this will place the script at the bottom just before the </body> tag and make sure you are not calling the function before your bundles load.
#section scripts {
<script>
$(document).ready(function() {
var clients = new Bloodhound({
datumTokenizer: function (datum) {
return Bloodhound.tokenizers.whitespace(datum.value);
},
queryTokenizer: Bloodhound.tokenizers.whitespace,
remote: {
url: "/info/client?like=%QUERY",
wildcard: '%QUERY',
filter: function (clients) {
return $.map(clients, function (client) {
return {
value: client.Name,
clientId: client.Identifier
};
});
}
}
});
clients.initialize();
$('#comp-name').typeahead(null,
{
display: 'value',
minLength: 1,
source: clients.ttAdapter(),
templates: {
empty: "Looks like a new client...",
suggestion: Handlebars.compile("<p><b>{{value}}</b> - {{clientId}}</p>")
}
});
});
</script>
}

Related

Chrome Extension: How to communicate with Content.js from a newly opened Window?

I have created a new window in chrome.action.onClicked.addListener as given below.
On clicking of "Check" button in newly opened window I need to connect to content.js and print some message in the console of window. I dont know where it is going wrong! I am using Manifest version 3.
content.js
chrome.runtime.onMessage.addListener(function(msg, sender, sendResponse) {
if(msg.color === "#00FF00"){
document.body.style.backgroundColor = "green";
sendResponse({ status: "done" });
}
});
background.js
var urlRegex = /^(https?:\/\/)?[a-z0-9-]*\.?[a-z0-9-]+\.[a-z0-9-]+(\/[^<>]*)?$/;
chrome.action.onClicked.addListener(function(tab) {
/*...check the URL of the active tab against our pattern and... */
if (urlRegex.test(tab.url)) {
/* ...if it matches, send a message specifying a callback too */
chrome.windows.create({
tabId: tab.id,
type:"popup",
url:"popup.html",
focused:true
});
}
});
popup.html
<html>
<head>
<script defer src="popup.js"></script>
</head>
<body>
<h3>Test Extension Page</h3>
<input type="button" id="sendMessage" value="Check"/>
</body>
</html>
popup.js
let sendMessageButton = document.getElementById("sendMessage");
console.log(document.URL);
console.log(sendMessageButton.value);
function getTitle()
{
return document.title;
}
sendMessageButton.onclick = function() {
chrome.tabs.query({ active: true, currentWindow: true }, function(tabs){
var tab = tabs[0];
chrome.scripting.executeScript(
{
target: {tabId:tab.id},
func: getTitle,
},
() => {
// This executes only after your content script executes
chrome.tabs.sendMessage(
tab.id,
{ color: "#00FF00" },
function (response) {
console.log(response.status);
}
);
});
});
};
Error in console of newly opened window.
Unchecked runtime.lastError: Cannot access contents of url "chrome-extension://jjaaoafdfmabdajdckiacompibnnmnlh/popup.html". Extension manifest must request permission to access this host.
Error handling response: TypeError: Cannot read properties of undefined (reading 'status') at chrome-extension://jjaaoafdfmabdajdckiacompibnnmnlh/popup.js:25:34
Unchecked runtime.lastError: Could not establish connection. Receiving end does not exist.
The problem is that the window you create becomes active and hence it becomes the result of chrome.tabs.query in your code, meaning that executeScript runs inside your own extension page, which can't work as this method is only for web sites.
The solution is to pass the tab id as URL parameter.
// background.js
chrome.action.onClicked.addListener(tab => {
chrome.windows.create({
type: 'popup',
url: 'popup.html?' + new URLSearchParams({
tabId: tab.id,
title: tab.title,
}),
});
});
// popup.js
const params = new URLSearchParams(location.search);
const tabId = +params.get('tabId');
let title = params.get('title'); // initial title
document.getElementById('sendMessage').onclick = async function () {
title = (await chrome.tabs.get(tabId)).title;
let res = await chrome.tabs.sendMessage(tabId, { color: "#00FF00" });
};

Chrome Extenstion with Vue Invoking nested methods

thanks to all in advanced.
I'm trying to build a simple Chrome extension with vue using this Boilerplate,
but I find it hard to communicate with the content.js file and popup.js file and passing data between them.
currently I'm trying to pass the total number of p tags that are in the current tab.
when I try to invoke a method inside the sendMessage function I'm getting an Error saying this.count is not a function. I'v figured out that probably the function is not firing because it's nested, but I cant figure out how can invoke the method.
Cheers to all
popup.js
<template>
<div>
<p>{{title}}</p>
<button v-on:click="getCount">click Here</button>
<p>{{counts}}</p>
</div>
</template>
<script>
export default {
data() {
return {
title: "count board",
counts: ""
};
},
methods: {
getCount() {
chrome.tabs.query({ currentWindow: true, active: true }, tabs => {
chrome.tabs.sendMessage(tabs[0].id, "null", this.count);
});
}
},
count(res) {
console.log(res.count);
this.counts = res.count
}
};
</script>
Content.js
chrome.runtime.onMessage.addListener(function (req, sender, sendResponse) {
const para = document.querySelectorAll('p')
sendResponse({ count: para.length })
})
I'm trying to invoke this.count on every button click in popup.html and retrieving the total numbers of P tags

Vue.Js Beginner about Component

I have a little problem with my code and need some advice.
I try to simulate a diceroll with Vue.js. To be sure any diceroll is different, i want to create a component for that. I use that code for my app.js
Vue.component('diceroll', {
template: 'This is the result !' + diceroll,
data: function() {
return {
diceroll: 0
}
},
methods: function(){
diceroll: Math.floor(Math.random() * 6) + 1;
}
}
)
var demo = new Vue( {
el: ' #demo',
}
)
Obviously, it don't work and i don't understand how to do that. I read the doc and watch the laracast's series but...
Someone can help me on this ? ^^
"methods" in Vue are actually objects (key-value pair) where the value is a function. Also, inside the template you have to refer variables using mustache binding like this: {{ vName }}.
I made example: (here is a jsbin demo)
Vue.component('diceroll', {
template: 'This is the result: {{diceroll}}',
data: function() {
return {
diceroll: 0
};
},
methods: {
roll: function() {
this.diceroll = Math.floor(Math.random() * 6) + 1;
}
},
ready: function() {
this.roll();
}
});
var demo = new Vue({
el: '#demo'
});
<script src="http://vuejs.org/js/vue.js"></script>
<div id="demo">
<diceroll></diceroll>
</div>

Chrome onMessage not working (?)

I've read about onMessage.addListener method in Chrome to pass some data from extensions to script. What I have now:
popup.js
window.onload = function(){
document.getElementById('searchButton').onclick = searchText;
};
function searchText(){
var search = document.getElementById('searchText').value; // f.ex "123"
if(search){
chrome.tabs.query({active:true,currentWindow:true},function(tabs){
chrome.tabs.executeScript(tabs[0].id,{file:search.js});
chrome.tabs.sendMessage(tabs[0].id,{method:'search',searchText:search});
});
}
}
search.js
chrome.runtime.onMessage.addListener(function(message,sender,sendResponse){
alert('text');
});
However, alert ('text') is never fired. What's the problem?
You should quote "search.js" and put the chrome.tabs.sendMessage call in the callback of chrome.tabs.executeScript:
function searchText(){
var search = document.getElementById('searchText').value; // f.ex "123"
if (search) {
chrome.tabs.query({active:true,currentWindow:true}, function(tabs) {
chrome.tabs.executeScript(tabs[0].id, {
file: 'search.js'
}, function() {
chrome.tabs.sendMessage(tabs[0].id, {
method: 'search',
searchText: search
});
});
});
}
}
If this suggestion does not help, inspect the popup and look for error messages.

Footer's contents don't seem to work

I'm trying create custom footers such in phantomjs examples: https://github.com/ariya/phantomjs/blob/master/examples/printheaderfooter.js
Here is my code:
var phantom = require('node-phantom');
phantom.create(function (err, ph) {
ph.createPage(function (err, page) {
page.set('paperSize', {
format: 'A4',
orientation: 'portrait',
footer: {
contents: ph.callback(function (pageNum, numPages) {
if (pageNum == 1) {
return "";
}
return "<h1>Header <span style='float:right'>" + pageNum + " / " + numPages + "</span></h1>";
})
}
}, function () {
page.open('http://www.google.com', function () {
})
})
})
});
But unfortunately I get the following error:
TypeError: Object #<Object> has no method 'callback';
Is it bug that ph does not expose callback method?
There are two problems in your script :
ph is not the classic phantom object, but a proxy object. node-phantom use web sockets to invoke phantomjs. Of course, some features are lost using this implementation.
functions are not serialized when calling page.set
Printing custom header/footer also requires to call phantom.callback. This method is not documented and so not exposed by node-phantom (and can't be). We need to find a way to apply this method in this package.
There are many solutions. Here is my possible solution :
Serialize your functions in a string in your script
var phantom = require('node-phantom');
phantom.create(function (err, ph) {
ph.createPage(function (err, page) {
page.set('paperSize', {
format: 'A4',
orientation: 'portrait',
header: {
height: "1cm",
contents: 'function(pageNum, numPages) { return pageNum + "/" + numPages; }'
},
footer: {
height: "1cm",
contents: 'function(pageNum, numPages) { return pageNum + "/" + numPages; }'
}
}, function () {
page.open('http://www.google.fr', function () {
page.render('google.pdf');
ph.exit();
})
})
})
});
edit bridge.js and add phantom.callback + eval. This allow us to re-plug the header/footer .contents.
case 'pageSet':
eval('request[4].header.contents = phantom.callback('+request[4].header.contents+')');
eval('request[4].footer.contents = phantom.callback('+request[4].footer.contents+')');
page[request[3]]=request[4];
respond([id,cmdId,'pageSetDone']);
break;
As you can see this works ! (Google in French)
Unfortunately, node-phantom doesn't appear to support phantom.callback. Since the project is inactive for more than a year, I think it's unlikely to be updated in the near future.
On the other hand, phantomjs-node supports phantom.callback() since version 0.6.6. You can use it like this:
var phantom = require('phantom');
phantom.create(function (ph) {
ph.createPage(function (page) {
page.open("http://www.google.com", function (status) {
var paperConfig = {
format: 'A4',
orientation: 'portrait',
border: '1cm',
header: {
height: '1cm',
contents: ph.callback(function(pageNum, numPages) {
return '<h1>My Custom Header</h1>';
})
},
footer: {
height: '1cm',
contents: ph.callback(function(pageNum, numPages) {
return '<p>Page ' + pageNum + ' / ' + numPages + '</p>';
})
}
};
page.set('paperSize', paperConfig, function() {
// render to pdf
page.render('path/to/file.pdf', function() {
page.close();
ph.exit();
});
});
});
});
});
As you can also see on this gist.
node phantom seems to expose this proxy-object via the create function (this should be your ph-object):
var proxy={
createPage:function(callback){
request(socket,[0,'createPage'],callbackOrDummy(callback));
},
injectJs:function(filename,callback){
request(socket,[0,'injectJs',filename],callbackOrDummy(callback));
},
addCookie: function(cookie, callback){
request(socket,[0,'addCookie', cookie],callbackOrDummy(callback));
},
exit:function(callback){
request(socket,[0,'exit'],callbackOrDummy(callback));
},
on: function(){
phantom.on.apply(phantom, arguments);
},
_phantom: phantom
};
that means, that you can probably acces the phantoms callback like this:
ph._phantom.callback
Here what I did to access phantom.callback:
add this to node-phantom.js line 202:
callback: function(callback){
request(socket,[0,'callback'],callbackOrDummy(callback));
},
just before _phantom: phantom
and add this to bridge.js line 45:
case 'callback':
phantom.callback(request[3]);
break;
Hope it helps!

Resources