extract text from pdf in chrome extensions - javascript

I am developing a chrome extensions. What i want to realize is that the popup can display the text from pdf. I have searched the PDF.js and write the following code in backgroud.js of chrome extensions to test:
‘use strict’;
var pdf = PDFJS.getDocument('http://www.pacer.gov/documents/pacermanual.pdf');
var pdf = PDFJS.getDocument('pacermanual.pdf');
pdf.then(function(pdf) {
var maxPages = pdf.pdfInfo.numPages;
for (var j = 1; j <= maxPages; j++) {
var page = pdf.getPage(j);
// the callback function - we create one per page
var processPageText = function processPageText(pageIndex) {
return function(pageData, content) {
return function(text) {
// bidiTexts has a property identifying whether this
// text is left-to-right or right-to-left
for (var i = 0; i < text.bidiTexts.length; i++) {
str += text.bidiTexts[i].str;
}
if (pageData.pageInfo.pageIndex ===
maxPages - 1) {
// later this will insert into an index
console.log(str);
}
}
}
}(j);
var processPage = function processPage(pageData) {
var content = pageData.getTextContent();
content.then(processPageText(pageData, content));
}
page.then(processPage);
}
});
The manifest is shown as follow:
{
"name": "englishhelper",
"version": "0.0.1",
"description": "",
"permissions": [
"tabs", "http://*/*", "https://*/*"
],
"background":{
"script":["background.js","PDF.js"]
},
"browser_action":{
"default_icon":"icon_png",
"default_popup":"popup.html"
},
"manifest_version": 2
}
The popup.html is shown as follow:
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="popup.css">
<title></title>
</head>
<body>
<script src="background.js"></script>
<script src="PDF.js"></script>
</body>
</html>
The console shows that "PDFJS is not defined". The "PDF.js" has been included in popup.html. Is it possible that chrome extension use PDF.js?

Wrong load order. (Do we have a canonical question for that?)
background.script or content_scripts[i].js key in the manifest is an array, in other words an ordered list.
Scripts are loaded and executed in the sequence defined there; you need to make sure libraries are loaded before they are used.
In your case, you need to swap them around:
"background":{
"script": ["PDF.js", "background.js"]
},
Same applies to the order of <script> tags in HTML, for instance in your popup.html

Related

How to access data from amazon page and replace with the converted values using Chrome Extension

So what I wanna do is to get CAD from amazon.ca and convert them into INR. Now I've figured out how to get data from amazon.ca using a dummy page on localhost and apply the converted value, but the thing is, IDK how to apply it so that it starts converting and replacing the data from amazon.ca instead of localhost. The folowing is what I did till now.
content.js
async function exchangeCurrency() {
// Fetchs INR and puts in curVal
var url = "https://cdn.jsdelivr.net/gh/fawazahmed0/currency-api#1/latest/currencies/cad.json"
let obj = await(await fetch(url)).json()
var curVal = obj.cad["inr"]
// Gets CAD Dollar and Cents
var cadPriceWhole = document.getElementsByClassName("a-price-whole")
var cadPriceFraction = document.getElementsByClassName("a-price-fraction")
for(var i = 0; i<cadPriceWhole.length; i++){
var wCAD = parseInt(cadPriceWhole[i].innerHTML.replace(/[^0-9]/g,''))
var fCAD = parseInt(cadPriceFraction[i].innerHTML.replace(/[^0-9]/g,''))
var inr = parseInt((wCAD + (fCAD/100)) * curVal)
cadPriceFraction[i].innerHTML = ""
cadPriceWhole[i].innerHTML = cadPriceWhole[i].innerHTML + " - " + inr.toLocaleString()
}
}
window.addEventListener('load', function () {
console.log("Poopz Here")
exchangeCurrency()
});
manifest.json
{
"name": "Amzn CAD-INR",
"version": "1.0.0",
"description": "Convert CAD to INR in Amazon",
"manifest_version": 3,
"author": "AZZIOI"
}
dummy page
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
</head>
<body>
<span class="a-price-whole">1,279<span class="a-price-decimal">.</span></span>
<span class="a-price-whole">879<span class="a-price-decimal">.</span></span>
<span class="a-price-whole">989<span class="a-price-decimal">.</span></span>
<span class="a-price-fraction">78</span>
<span class="a-price-fraction">45</span>
<span class="a-price-fraction">69</span>
</body>
<script src="content.js"></script>
</html>
Please use content_scripts.
For example:
manifest.jsion
{
"name": "hoge",
"version": "1.0",
"manifest_version": 3,
"content_scripts": [
{
"matches": [
"https://www.amazon.ca/*"
],
"js": [
"matches.js"
]
}
]
}}
matches.js
Write your script here.

Need Help Display DOM Content For Google Chrome Extension

I am creating a Google Chrome Extension that uses a script that works perfectly well in Google Chrome's console.
However, I am trying to use this same script beyond just printing the information in console.
How would I be able to somehow create HTML elements that contain this information within the popup.html page? I know that this idea might have to use the callback function within
Here is my code:
manifest.json
{
"manifest_version": 2,
"name": "MR QC Auditor View",
"version": "1.0",
"description": "This Google Chrome extension shows Ad ID's for print ads, and then links to Ad Tagger for tagging corrections",
"icons": {
"128": "MRLogo128.png",
"48": "MRLogo48.png",
"16": "MRLogo16.png"
},
"browser_action":{
"default_icon": "MRLogo16.png",
"default_popup": "popup.html"
},
"permissions": [
"storage",
"tabs",
"activeTab"
]}
popup.html:
<!DOCTYPE html>
<html>
<head>
<title>MR QC Auditor View</title>
<script src="jquery-3.3.1.min.js">
</script>
<script src="popup.js">
</script>
</head>
<body>
<img src="MRLogo128.png"/>
<h1>Current Ad's Brand: <h1><span id="brandNameText"></span>
<h2>Link To Ad Tagger</h2><span>Link</span>
</body>
</html>
popup.js:
// Current Post To Look At:
// https://stackoverflow.com/questions/4532236/how-to-access-the-webpage-dom-rather-than-the-extension-page-dom
// Related Google + Group Post:
// https://groups.google.com/a/chromium.org/forum/#!topic/chromium-extensions/9Sue8JRwF_k
// Use chrome.runtime.onMessage()
// Documentation:
// https://stackoverflow.com/questions/3010840/loop-through-an-array-in-javascript
// chrome.tabs.executeScript():
// https://developer.chrome.com/extensions/tabs#method-executeScript
/*
Old Code Block;
chrome.tabs.executeScript({file: 'jquery-3.3.1.min.js'}, function () { chrome.tabs.executeScript({code: 'var printAds = document.getElementsByClassName("ad-image printadviewable pointer"); ', allFrames: true}, function(stuff){
chrome.runtime.sendMessage({greeting: "hello"}, function(){
// Call chrome.runtime.sendResponse()
// console.log("DOM Content Sent To Chrome Extension Webpage");
})
}}); });
*/
// Added an array called "adArray" that utilizes the .push() JavaScript array function
// I need to somehow add this to the popup.html page itself, look for the StackOverflow related pages.
chrome.tabs.executeScript({file: 'jquery-3.3.1.min.js'}, function (adArray) { chrome.tabs.executeScript({code: 'var printAds = document.getElementsByClassName("ad-image printadviewable pointer"); var adArray = []; for (var i = 0; i<printAds.length; i++){console.log("Current Ad Id = " + $(printAds[i]).attr("data-adid")); adArray.push($(printAds[i]).attr("data-adid"))}', allFrames: true}); });
/*
Console Based Code That Works:
$("#ad-image printadviewable pointer").find("img").attr("data-adid");
var printAds = document.getElementsByClassName("ad-image printadviewable pointer");
for (var i = 0; i<printAds.length; i++){console.log("Current Ad Id = " + $(printAds[i]).attr("data-adid"));}
*/
// One Line Version For Code Dictionary Key
// 'var printAds = document.getElementsByClassName("ad-image printadviewable pointer"); for (var i = 0; i<printAds.length; i++){console.log("Current Ad Id = " + $(printAds[i]).attr("data-adid"));}'

chrome extension. JS not running [duplicate]

This question already has answers here:
onclick or inline script isn't working in extension
(5 answers)
Closed 5 years ago.
I am trying to create a Chrome extensions that perform an Autocomplete functio on an input field.
First please have a look and the function code on a normal HTML page
<!DOCTYPE html>
<html>
<head>
<title>Testing autocomplete</title>
<script>
var people = ['Fabio', 'Marco', 'Pietro', 'Kucio', 'Pato'];
function matchPeople(input) {
var reg = new RegExp(input.split('').join('\\w*').replace(/\W/, ""), 'i');
return people.filter(function(person) {
if (person.match(reg)) {
return person;
}
});
}
function changeInput(val) {
var autoCompleteResult = matchPeople(val);
var text = "";
var i;
for (i = 0; i < autoCompleteResult.length; i++) {
text += autoCompleteResult[i] + "<br>";
}
document.getElementById("result").innerHTML = text;
}
</script>
</head>
<body>
<input type="text" onkeyup="changeInput(this.value)">
<div id="result"></div>
</body>
</html>
Now, if we run this code on any webpage it works just fine.
The issue I am having is to move the above functions in a Chrome Extension.
I have my manifest.json here:
{
"name": "AutoComplete UZ",
"version": "1.0",
"description": "Provides with a small popup window with the AutoComplete function with UZ internal emails.",
"browser_action": {
"default_popup": "popup.html",
"default_title": "UZ AutoComplete"
},
"content_scripts": [
{
"matches" : ["http://*/*", "https://*/*"],
"css": ["style.css"],
"js" : ["popup.js"]
}
],
"manifest_version": 2
}
My popup.html file here:
<!DOCTYPE html>
<html>
<head>
<title>UZ AutoComplete</title>
<link rel="stylesheet" type="text/css" href="style.css">
<script src="popup.js"></script>
</head>
<body>
<h1>UZ AutoComplete</h1>
<h3>Type email address</h3>
<input id="amount" type="text" onkeyup="changeInput(this.value)" placeholder="your email">
<div id="result"></div>
</body>
</html>
and my popup.js file here:
var people = [
'Fabio',
'Marco',
'Pietro',
'Kucio',
'Pato'
];
function matchPeople(input) {
var reg = new RegExp(input.split('').join('\\w*').replace(/\W/, ""), 'i');
return people.filter(function(person) {
if (person.match(reg)) {
return person;
}
});
}
function changeInput(val) {
var autoCompleteResult = matchPeople(val);
var text = "";
var i;
for (i = 0; i < autoCompleteResult.length; i++) {
text += autoCompleteResult[i] + "<br>";
}
document.getElementById("result").innerHTML = text;
}
If I pack the above files and create an Extension, the above code will not work. I see the popup.html input field but the functions that make the magic won't trigger and I do not understand why.
I do not think I need an event.js page to run the above simple functions but please let me know the best approach for this. Hope I was clear enough on what I am trying to achieve.
Any help is more than welcome stackoverflowers!
Google Chrome extensions do not allow inline Javascript.
You'll need to to add an event listener in your popup.js instead.
document.querySelector('#amount').addEventListener('keyup', function() {
//get input's value and call your functions here
});

Chrome App not showing Base64 encoded PDF in Iframe

I'm developing a Chrome App which is a wrapper for the main app in webview. The webview sends Base64 encoded PDF as a message to the app and the app creates a hidden iframe, loads the PDF in to the frame and calls print on the frame.
This all works on my development machine (Win10, Chrome Beta v47) but does not work on any other machine or Chrome version I've tried. The iframe does not show the PDF so a blank page is shown in the print preview.
What can cause this? Is there some setting or permission which I might have enabled on my machine?
Here is a simplified Chrome App that I have used to reproduce the problem.
manifest.json
{
"manifest_version": 2,
"version": "2",
"name": "Print PDF test",
"app": {
"background": {
"scripts": ["main.js"]
}
},
"permissions": [
]
}
main.js
chrome.app.runtime.onLaunched.addListener(function() {
chrome.app.window.create('index.html', {
innerBounds: {
width: 768,
height: 1024
}
});
});
index.html
<!DOCTYPE html>
<html style="height: 100%">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Print PDF</title>
</head>
<body style="height: 100%">
</body>
<script src="app.js"></script>
</html>
app.js
function showPDF() {
var base64pdf = 'JVBERi0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==';
var blobPdf = new Blob([base64ToUint8(base64pdf)], {
type: 'application/pdf;base64'
});
var pdfFrame = document.createElement('iframe');
pdfFrame.id = 'pdfFrame';
pdfFrame.style.width = "100%";
pdfFrame.style.height = "100%";
pdfFrame.src = URL.createObjectURL(blobPdf);
document.body.appendChild(pdfFrame);
}
function base64ToUint8(base64str) {
var binary = atob(base64str.replace(/\s/g, ''));
var len = binary.length;
var buffer = new ArrayBuffer(len);
var view = new Uint8Array(buffer);
for (var i = 0; i < len; i++) {
view[i] = binary.charCodeAt(i);
}
return view;
}
document.addEventListener('DOMContentLoaded', function() {
showPDF();
});
I finally found the answer to my question.
I had checked the "Always allowed" checkbox for Chrome PDF Viewer in chrome://plugins/ on my development machine. That is why it was not working on other machines.

javascript objects cant see each other? :: google chrome extension

i have two files
one called stats.js
one called storage.html
in stats.js in contains
var stats = {
myFunc : function() {
//do something
}
}
in storage.html I have
<html>
<head>
<script src="stats.js"></script>
<script>
$(document).ready(function() {
stats.myFunc();
});
</script>
</head>
</html>
But I get
Uncaught TypeError: Cannot call method 'myFunc' of undefined
Update
Ok so that was a really simplified example.
The basics of it are,
This is a google chrome extension, So you will see some code specific to that.
Here is the literal pages concerned:
Popup.html
<html>
<head>
<title>Extension</title>
<script src="http://code.jquery.com/jquery-1.4.2.min.js"></script>
<script src="js/popup.js"></script>
<script src="js/statsapi.js"></script>
<link type="text/css" rel="stylesheet" href="css/popup.css" />
</head>
<body>
<div id="content">
</div>
</body>
</html>
popup.js
$(document).ready(function() {
if(background.storage.get('firstRun') == null)
background.initialize();
if(background.storage.get('metaExpire') >= Date.parse(Date()))
background.updateMeta();
$('#content').append(read_object(stats.getMetaData()));
});
function read_object(object){
var $obj = $('<div />');
for(var o in object) {
$obj.append(o+' : ');
if(typeof(object[o]) == 'object' && object[o] != null)
$obj.append(read_object(object[o]));
else
$obj.append(object[o]+'<br />');
}
return $obj;
}
Manifest.json
{
"name": "Halo Reach: Stats",
"description": "This extension allows you to keep track of your own, and your friends Halo Reach Stats.",
"version": "1.0.0.1",
"permissions": [
"http://www.bungie.net/"
],
"icons": {
"128": "images/logo/logo128.jpg",
"64": "images/logo/logo64.jpg",
"32": "images/logo/logo32.jpg",
"16": "images/logo/logo16.jpg"
},
"browser_action": {
"default_title": "Open Stats",
"default_icon": "images/logo/logo32.jpg",
"popup": "popup.html"
},
"background_page": "background.html"
}
statsapi.js
var background = chrome.extension.getBackgroundPage();
var apikey = background.storage.get('apikey');
var gamertage = background.storage.get('gamertag');
var page = '0';
var stats = {
getMetaData : function() {
var url = 'http://www.bungie.net/api/reach/reachapijson.svc/game/metadata/'+apikey;
console.log(url);
$.ajax({
url: url,
success: function(data) {
return data;
}
});
},
meta : {
read : function(param) {
var meta = background.storage.get('metaData');
}
}
};
Background.html
<html>
<head>
<script src="js/statsapi.js"></script>
<script>
var storage = {
set : function (key, value) {
window.localStorage.removeItem(key);
window.localStorage.setItem(key, value);
},
get : function (key) {
return window.localStorage.getItem(key);
},
clear : function () {
window.localStorage.clear();
}
};
function updateMeta() {
var meta = stats.getMetaData();
if(meta['status'] == 0){
storage.set('metaData', JSON.stringify(meta));
storage.set('metaExpire', Date.parse(Date())+900000);
}
}
function initialize() {
storage.set('apikey', '***');
storage.set('gamertag', 'The Hailwood');
updateMeta();
}
</script>
</head>
</html>
When the extension is invoked it calls popup.html
and the document ready javascript is invoked.
The check for first run fails,
so it calls initialize() in background.html
But this is where the error occurs.
the actual error is
Uncaught TypeError: Cannot call method 'getMetaData' of undefined.
So why can it not see the stats class?
its not a script include problem as if the path is wrong for the statsapi.js I get
Uncaught ReferenceError: stats is not defined.
The issue seems to be with the var stats {} as if under that I have a function called test() I can call that fine :/
Hmm,
is there an issue because it is an external stylesheet?
I suspect the error lies somewhere else - these are my examples:
mark#localhost:~/ccsite$ cat cat.js
var stats = {
myFunc : function() {
alert('wtf');
}
}
mark#localhost:~/ccsite$ cat hat.htm
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script src="cat.js"></script>
<script>
$(document).ready(function() {
stats.myFunc();
});
</script>
</head>
</html>
Viewing hat.htm in either FF, IE6 or Chrome produces the alert, 'wtf'. As written you'd get $ is undefined, since it's not including jQuery of course, so I added that.
So, your problems likely are elsewhere. I assume this is a simplified example - what else is going on in your page?
This is because there is some syntax error in your code. I had same problem. I opened my background.html page in fire fox with fire-bug plug-in enabled. Fire-bug console should me the error, I fixed and it is working now.
I have suspicions that it's because you include js/statsapi.js script into both your popup and background page, so it gets confused which stats you are referring to as you have 2 of them in the popup - one included through script tag and another one loaded from background page after you call chrome.extension.getBackgroundPage()

Categories