I'm totally new to browser extensions. I've had some success making a simple extension that automatically changes webpage content, and now I want it to change that content after querying the server for a true or false value. I'm trying to do this with an AJAX request (pure javascript). For some reason, I can't get any information out of the PHP script on the server with which my browser extension is interacting.
Manifest:
{
"manifest_version": 2,
"name": "Truth Seeker",
"version": "1.0",
"description": "Returns true.",
"icons": {
"48": "icons/icon.png"
},
"content_scripts": [
{
"matches": ["*://*/*"],
"js": ["script.js"]
}
]
}
Script:
theBool = false;
url = /* PHP URL HERE */;
string = "";
request(MakeOutput, url, string);
if(theBool == true){
alert("is true");
}
function MakeOutput(x){
if(x == "true"){
theBool = true;
}
}
function request(fix, url, string){
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
fix(xhttp.responseText);
}
}
xhttp.open("POST", url, true);
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttp.send(string);
}
The PHP file on the server just echos "true" at the moment. If I access that PHP script directly (by typing the URL into the browser), it will alert "is true". Why will it do it but no other pages will?
Well, I tore my hair out on this for a while, gave up on myself, asked a question, and then figured the answer out on my own within a few more minutes. To help anyone else in the future, I added this to the manifest:
"permissions": [
"webRequest",
"<all_urls>"
],
Related
I am developing a Configurable Tab to be used for meetings. I need to call getContext in order to retrieve the meetingId so that I know which meeting the tab is running in. All works well on desktop - getContext calls the callback function and returns the context. On mobile, though, the callback function is never called.
Here is the configurableTabs section of the manifest (configuration works fine without an issue):
"configurableTabs": [
{
"configurationUrl": "https://xxx.xxx.xxx/teams-app/meetingConfig.html",
"scopes": [
"team",
"groupchat"
],
"canUpdateConfiguration": true,
"context":[
"meetingChatTab",
"meetingDetailsTab",
"meetingSidePanel",
"meetingStage"
]
}
],
And here is the code calling getContext (this is from within the page loaded after configuration is saved and completed):
(async () => {
'use strict';
try {
microsoftTeams.initialize();
microsoftTeams.getContext( async function (context) {
document.getElementById("app").innerHTML += "<br/><br/>Return from context " + JSON.stringify(context); //this is never called
if (!!context && context.chatId) {
meetingId = context.chatId;
await initializeMeetingInfo();
store.dispatch('setMeetingInfo', meetingInfo);
initializeVue();
} else {
document.getElementById("app").innerHTML += "<br/><br/>Unable to get meeting Id. Context=" + JSON.stringify(context);
});
} catch (e) {
document.getElementById("app").innerHTML += "<br/><br/>" + 'teams getContext error: ' + JSON.stringify(e);
}
Any idea why getContext isn't calling the callback function on mobile (android Pixel 5)?
Thank you
Moving the answer from comments to answers section.
Could you please try the below sample code,
Script:
var app = angular.module('DemoApp', []) app.controller('myController', function ($scope) { $scope.load = function () { microsoftTeams.initialize(); microsoftTeams.getContext(context => { alert(JSON.stringify(context)); }); } }); HTML: This is a sample code.
I am using Laravel for site development purposes. What would be nice is to have a button on the main page that shows the current version of the project. When clicking on the button, one would see all of the changes that have taken place (in the form of git commits) to the system. Is there a way to do this? If so, how?
TIA
On click of the button initiate an ajax call
$("#button").on("click", function () {
url: window.location.origin + '/fetch-git-commits',
type: "get",
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
success: function (data) {
// data contains the git commit informations
$(".container").html(data);
}
});
In the Route.php file add an entry
Route::get('fetch-git-commits', 'YourController#getGitCommits');
In the controller
public function getGitCommits ()
{
exec('git log', $output);
$history = array();
foreach($output as $line) {
if(strpos($line, 'commit') === 0) {
if(!empty($commit)) {
array_push($history, $commit);
unset($commit);
}
$commit['hash'] = substr($line, strlen('commit'));
}
else if(strpos($line, 'Author') === 0) {
$commit['author'] = substr($line, strlen('Author:'));
}
else if(strpos($line, 'Date') === 0) {
$commit['date'] = substr($line, strlen('Date:'));
}
else {
if(isset($commit['message']))
$commit['message'] .= $line;
else
$commit['message'] = $line;
}
}
return $history; // Array of commits, parse it to json if you need
}
References:
Reading a git commit message from php
Parse git log with PHP to an array
There is a little package for that:
https://github.com/tremby/laravel-git-version
I am having an issue trying to use the addInitialFiles method listed here:
http://docs.fineuploader.com/branch/master/api/methods.html#addInitialFiles
I get a javascript error in my chrome dev console that says:
1032:381 Uncaught TypeError: uploader.addInitialFiles is not a function
This is the code I use to initialize Fine Uploader, and make the call the addInitialFiles():
<script type="text/javascript">
$(function () {
var uploader = $('#fine-uploader').fineUploaderS3({
request: {
endpoint: "myfineuploaderbucket.com.s3.amazonaws.com",
accessKey: "XXXXXXXXXXXXXXXXXXXXXXXX",
},
signature: {
endpoint: "/SignatureHandler",
version: 4
},
validation: {
allowedExtensions: ["gif", "jpeg", "jpg", "png", "bmp"],
acceptFiles: "image/gif, image/jpeg, image/png, image/bmp",
sizeLimit: 5000000,
itemLimit: 3
},
retry: {
enableAuto: true
},
deleteFile: {
enabled: true,
endpoint: "/DeleteImage/?id=#Model.Id",
method: 'POST',
},
paste: {
targetElement: $(document),
promptForName: true
},
uploadSuccess: {
endpoint: "/UploadSuccessful/?id=#Model.Id"
},
iframeSupport: { //This path needs to be a blank HTML page and is used for fine-uploader to support IE9 and older
localBlankPagePath: "/Blank"
},
objectProperties: {
acl: "public-read",
key: function (fileId) {
var re = /(?:\.([^.]+))?$/;
fileExt = re.exec($("#fine-uploader").fineUploader("getName", fileId))[0];
uuid = $("#fine-uploader").fineUploader("getUuid", fileId);
filename = uuid + fileExt;
key = "/#ViewBag.Id + "/" + filename;
return key;
}
},
scaling: {
hideScaled: true,
sizes: [
{ name: "small", maxSize: 350 },
{ name: "large", maxSize: 800 },
]
},
callbacks: {
onDelete: function (id) {
if (id == 2) {
$("#fine-uploader").fineUploader("deleteFile", 0);
$("#fine-uploader").fineUploader("deleteFile", 1);
}
},
},
});
uploader.addInitialFiles([
{
"name": "a3ef2360-881d-452c-a5f6-a173d5291066.jpg",
"uuid": "a3ef2360-881d-452c-a5f6-a173d5291066",
"size": "66000",
"thumbnailUrl": "https://s3.amazonaws.com/myfineuploaderbucket.com/1032/ecdca7bb-fb02-4072-b526-4e51cedb1f2b.jpg",
"s3Key": "1032/a3ef2360-881d-452c-a5f6-a173d5291066.jpg",
"s3Bucket": "myfineuploaderbucket.com"
}
]);
Is there something that I am doing wrong? Is addInitialFiles not a method, but an option that needs to be initialized when creating the Fine Uploader instance? I have tried adding "addInitialFiles" to the options of the Fine Uploader instance as well, and I do not receive a javascript error, but it does not load the initial file either.
I am using the latest version, 5.7.1.
Just like any other jQuery plug-in, the Fine Uploader jQuery wrapper returns a jQuery-wrapped element. This means that you are attempting to call an addInitialFiles method on a jQuery object. Of course, this method does not exist. If you really want to continue using the jQuery wrapper, you must change uploader.addInitialFiles(...) to uploader.fineUploaderS3('addInitialFiles', ...).
But you should know that you don't need jQuery for any of this, especially when using Fine Uploader. There is no benefit to using the jQuery wrapper with Fine Uploader, and you can fix your code simply by forgoing the wrapper (and saving a few bytes) and changing the first couple lines of your Fine Uploader initialization to:
var uploader = new qq.s3.FineUploader({
element: document.querySelector('#fine-uploader'),
...
})
Now, uploader.addInitialFiles works as you would expect.
I am working with data table plugin. Initially what I tried is to update the data table plugin from a flat text file. The text file would look like below.
{
"data":[
{
"reference":"#VIP-123",
"application":"Development Aspects",
"applicationType":"Current Application"
},
{
"reference":"#VIP-123",
"application":"Development Aspects",
"applicationType":"Current Application"
}
]
}
I have a HTML file inside this I am writing JavaScript like below.
$(document).ready(function() {
var table=$('#app-table').DataTable( {
"bProcessing": true,
"bPaginate":true,
"bServerSide": false,
"sAjaxSource": "./data/arrays.txt",
"deferRender": true,
"columns": [
{ "data": "reference" },
{ "data": "application" },
{ "data": "applicationType" },
],
"order": [[ 3, "desc" ]],
"ordering": true,
"bFilter": true
} );
The data table is rendering fine until am not having more than 20,000 rows in the table. As the number of rows will increase in the table then data table took more time to load.
What I notices by going through with several site is that we can reduce the load time by using server side processing and for that I need to go with a server which is not possible in my case because I am rendering data from a flat text file. Then I thought to look for static data storage.
So coming to the problem is using indexedDB can we resolve the performance issue and if answer is yes than can anyone let me know how?
I am able to work with indexedDB but unable to integrate with jQuery data table. I mean what I need to make change in the JavaScript. If we can make server side processing with indexedDB then what will be the script?
first read your local file in the following manner:
var rawFile = new XMLHttpRequest();
rawFile.open("GET", file, false);
rawFile.onreadystatechange = function ()
{
if(rawFile.readyState === 4)
{
if(rawFile.status === 200 || rawFile.status == 0)
{
var allText = rawFile.responseText;
}
}
}
Then, use JQuery to parse "allText" into JSON.
Refer this link for parsing into JSON.
Now, create database using "indexedDB API" as mentioned below:
var request = indexedDB.open("<mention_your_db_name_here");
request.onupgradeneeded = function() {
// The database did not previously exist, so create object stores and indexes.
var db = request.result;
var store = db.createObjectStore("books", {keyPath: "reference"});
var titleIndex = store.createIndex("by_reference", "reference", {unique: true});
// Populate with initial data.
store.put({reference: "#VIP-123", application: "Development Aspects", applicationType: "Current Application"});
};
request.onsuccess = function() {
db = request.result;
};
for more details on "indexedDB API", please refer this link
So I'm trying to use AJAX to load some data. I can get the data to load but it's stuck in json. How do I make it so it's cleaner & more human readable?
//jquery
$.get("/get_artwork", function(data) {
var obj = jQuery.parseJSON(data)
$('.result').append("<br/> " + data + " ");
});
#Views.py
def get_artwork(request):
if request.is_ajax():
artwork = Artwork.objects.all()[1:]
if request.method == 'GET':
data = serializers.serialize("json", artwork, fields=('name','updated'), indent=2, use_natural_keys=True)
return HttpResponse(data,mimetype='application/javascript')
elif request.method == 'POST':
message = "This is an XHR POST request"
# Here we can access the POST data
print request.POST
else:
message = "Hello"
return HttpResponse(message)
and this is what renders:
[ { "pk": 3, "model": "artworks.artwork", "fields": { "updated": "2013-01-20T06:46:24Z" } }, { "pk": 2, "model": "artworks.artwork", "fields": { "updated": "2013-01-17T23:44:26Z" } }, { "pk": 1, "model": "artworks.artwork", "fields": { "updated": "2013-01-17T23:43:22Z" } } ]
How would I make this more human-readable? Thanks!
Based on the comments you've left.. it seems your issue is downstream in the client (e.g. web browser). It is not clear what you mean by stuck in JSON. If you are using JavaScript to parse the JSON, you will need to use JSON.parse() to turn it into a native JavaScript object. If you are using jQuery and the $.ajax() method, you will need to set the mimetype to application/json for it to automatically parse it as JSON.
UPDATE
If you want to control how the JSON data is rendered in the browser, I suggest you parse the JSON response into a native JavaScript object and then iterate over objects and fields you want to render in the page. As an example, using jQuery:
$.ajax({
url: '/some-url/',
dataType: 'json',
success: function(resp) {
var i, k, li, obj, fields;
for (i = 0; i < resp.length; i++) {
obj = resp[i];
// render obj pk or model name here... now iterate over fields
fields = obj.fields;
for (k of obj.fields) {
li = $('<li>').text(k + ': ' + obj.fields[k]);
// append the li to some element..
}
}
}
});