Chrome Extension Popup - Setting DIV text from background.js function - google-chrome-extension

Thank you for reading.
I am stuck on passing information between my background.js and popup.html!
In this example, I am trying to call testRequest in background.js from popup.html. I have looked at dozens of examples of how to do this and coded as many solutions, but I have not been successful...this is one of the solutions I tried:
Popup.html:
<html lang="en">
<head>
<meta charset="utf-8" />
<title></title>
</head>
<body>
<script type="text/javascript" src="background.js">
$(document).ready(function () {
document.getElementById("test").textContent = chrome.extension.getBackgroundPage.testRequest();
});
</script>
<div id="test"></div>
</body>
</html>
background.js
var testRequest = function(){
return 'yay!';
}
Your help is greatly appreciated!
~Brian

You could use simple message passing to do this. For example:
Popup.html
<html lang="en">
<head>
<meta charset="utf-8" />
<title></title>
<script src="jquery.min.js"></script>
<script src="popup.js"></script>
</head>
<body>
<div id="test"></div>
</body>
</html>
popup.js
$(function() {
chrome.runtime.sendMessage({method:"testRequest"},function(reply){
$('#test').text(reply);
});
});
background.js
chrome.runtime.onMessage.addListener(function(message,sender,sendRepsonse){
if(message.method == "testRequest")
sendResponse(testRequest());
});
function testRequest(){
return "yay!";
}
Inline code is not allowed in popup.html so we move it all to an external file, you were using jQuery already so don't be afraid to use it more, and if you are using it, don't forget to include it.

Related

How to use Google Analytics 4 inside chrome extension Manifest V3?

what I found out =>
you can't import scripts from links inside chrome extension's background scripts or content scripts (basically anywhere inside new page HTML or popup HTML)
so you what you need to do is =>
<html lang="en">
<head>
<script src="./googleAnalytics.js"></script>
<script src="./googleAnalyticsStarter.js"></script>
</head>
<body>
<noscript>You need to enable JavaScript to run this app.</noscript>
</body>
</html>
instead of =>
<html lang="en">
<head>
<script
async
src="https://www.googletagmanager.com/gtag/js?id=G-XXXXXXXX"
></script>
<script>
window.dataLayer = window.dataLayer || [];
function gtag() {
dataLayer.push(arguments);
}
gtag("js", new Date());
gtag("config", "G-XXXXXXXX");
</script>
</head>
<body>
<noscript>You need to enable JavaScript to run this app</noscript>
</body>
</html>

How to use preact using html and script tag?

I have a very simple react program that imports react using a script command and a cdn.
How do I covert it to preact while keeping the same structure?
I tried to follow these instruction, but they weren't very clear
<!DOCTYPE html>
<html>
<head>
<title></title>
<script src="https://unpkg.com/react#15/dist/react.js"> </script>
<script src="https://unpkg.com/react-dom#15/dist/react-dom.js"></script>
<script src="https://unpkg.com/babel-standalone#6.15.0/babel.js"></script>
</head>
<style type="text/css">
</style>
<body>
<div id='root'></div>
<script type="text/babel">
function T(props){
return <h1>{props.title}</h1>
}
ReactDOM.render(<T title='welcome'/>,document.getElementById('root'))
</script>
</body>
</html>
As per this github issue you have a couple of different options for using Preact with a script tag. You can directly call h- Preact's version of React.createElement or you can use babel standalone to transform your JSX as you were in your original React example. Here is a Preact conversion of your original example.
<!DOCTYPE html>
<html>
<head>
<title></title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/preact/7.2.0/preact.js"></script>
<script src="https://unpkg.com/babel-standalone#6.15.0/babel.js"></script>
</head>
<body>
<div id='root'></div>
<!-- option 1: alias it -->
<script>window.React = { createElement: preact.h }</script>
<script type="text/babel">
function T(props){
return <h1>{props.title}</h1>
}
preact.render(<T title="Welcome" />, document.getElementById('root'));
</script>
</body>
</html>

jQuery mobile app doesn't work on Android app created using PhoneGap [duplicate]

What is the correct way (to this date) to use JQuery Mobile and Phonegap together?
Both frameworks need to load before they can be used. How can I be sure that both are loaded before I can use them?
You can use deferred feature of JQuery.
var deviceReadyDeferred = $.Deferred();
var jqmReadyDeferred = $.Deferred();
document.addEventListener("deviceReady", deviceReady, false);
function deviceReady() {
deviceReadyDeferred.resolve();
}
$(document).one("mobileinit", function () {
jqmReadyDeferred.resolve();
});
$.when(deviceReadyDeferred, jqmReadyDeferred).then(doWhenBothFrameworksLoaded);
function doWhenBothFrameworksLoaded() {
// TBD
}
Here's how it worked for me, based on the example above
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<meta name="format-detection" content="telephone=no" />
<meta name="viewport" content="user-scalable=no, initial-scale=1, maximum-scale=1, minimum-scale=1, width=device-width, height=device-height, target-densitydpi=device-dpi" />
<link rel="stylesheet" type="text/css" href="css/bootstrap.css" />
<title>InforMEA</title>
</head>
<body>
<script type="text/javascript" src="js/jquery-1.8.3.js"></script>
<script type="text/javascript">
var dd = $.Deferred();
var jqd = $.Deferred();
$.when(dd, jqd).done(doInit);
$(document).bind('mobileinit', function () {
jqd.resolve();
});
</script>
<script type="text/javascript" src="js/jquery.mobile-1.2.0.js"></script>
<script type="text/javascript" src="cordova-2.2.0.js"></script>
<script type="text/javascript">
document.addEventListener('deviceready', deviceReady, false);
function deviceReady() {
dd.resolve();
}
function doInit() {
alert('Ready');
}
</script>
</body>
</html>
In order to use phonegap along with jquery mobile, you need to use it like this
<head>
<title>Index Page</title>
<!-- Adding viewport -->
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="viewport" content="width=device-width, user-scalable=no">
<!-- Adding jQuery scripts -->
<script type="text/javascript" src="jquery/jquery-1.7.1.min.js"></script>
<!-- Since jQuery Mobile relies on jQuery core's $.ajax() functionality,
$.support.cors & $.mobile.allowCrossDomainPages must be set to true to tell
$.ajax to load cross-domain pages. -->
<script type="text/javascript">
$(document).bind("mobileinit", function() {
$.support.cors = true;
$.mobile.allowCrossDomainPages = true;
});
</script>
<!-- Adding Phonegap scripts -->
<script type="text/javascript" charset="utf-8"
src="cordova/cordova-1.8.0.js"></script>
<!-- Adding jQuery mobile scripts & CSS -->
<link rel="stylesheet" href="jquerymobile/jquery.mobile-1.1.0.min.css" />
<script type="text/javascript"
src="jquerymobile/jquery.mobile-1.1.0.min.js"></script>
</head>
<script type="text/javascript">
// Listener that will invoke the onDeviceReady() function as soon as phonegap has loaded properly
document.addEventListener("deviceready", onDeviceReady, false);
function onDeviceReady() {
navigator.splashscreen.hide();
document.addEventListener("backbutton", onBackClickEvent, false); // Adding the back button listener
}
</script>
<body>
<div data-role="page" id="something" data-ajax="false">
<script type="text/javascript">
$("#something").on("pageinit", function(e) {
});
$("#something").on("pageshow", function(e) {
});
$("#something").on("pagebeforeshow", function(e) {
});
</script>
<div data-role="header">
</div>
<div data-role="content">
</div>
</div>
</body>
As many people suggested using a deferred is an okay option as long as you don't care what order deviceready and mobileinit happe in. But in my case, I needed a few pageshow events when the application first loaded and mobileinit and by extension those pageshow/pagebeforeshow/etc events were all firing before deviceready finished, so I couldn't bind to them properly using a deferred on them. This race condition was not a good thing.
What I needed to do was make sure 'mobileinit' didn't take place until after 'deviceready' was already fired. Because mobileinit fires immediately when you load JQM I chose to use jQuery.getScript to load it AFTER deviceready was already finished.
<script src="cordova-2.2.0.js"></script>
<script src="js/jquery-1.8.2.min.js"></script>
<script src="js/async.min.js"></script>
<script src="js/app.js"></script>
<script>
document.addEventListener(
'deviceready',
function () {
$('body').css('visibility', 'hidden');
$(document).one("mobileinit", function () {
app.init();
$('body').css('visibility', '');
});
$.getScript('js/jquery.mobile-1.2.0.min.js');
},
false
);
</script>
The reason I'm hiding the body is that a side effect of this method is a half second of visibility of the original HTML document before jquery.mobile loads. In this case hiding it an extra half second of empty space is preferred to seeing the unstyled document.
I believe that it isn't necessary to use the deferred feature. (Maybe this isn't necessary with newer versions of phonegap?) I have this in the head of my index.html file and everything works fine. I do think that the order of including jquery, phonegap and jquery mobile are important.
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<meta name="format-detection" content="telephone=no" />
<meta name="viewport" content="user-scalable=no, initial-scale=1, maximum-scale=1, minimum-scale=1, width=device-width, height=device-height, target-densitydpi=device-dpi" />
<!-- Adding jQuery -->
<script type="text/javascript" src="js/jquery-1.9.1.min.js"></script>
<!-- Add Phonegap scripts -->
<script type="text/javascript" src="phonegap.js"></script>
<!-- Add jQuery mobile -->
<link rel="stylesheet" href="css/jquery.mobile-1.3.2.css" />
<script type="text/javascript" src="js/jquery.mobile-1.3.2.min.js"></script>
<title>MY TITLE</title>
</head>
this is work for me. base on dhaval,this sample when I learn using sqlite
<!DOCTYPE html>
<html>
<head>
<title>Cordova Sqlite+Jquery</title>
<script type="text/javascript" charset="utf-8" src="js/jquery-1.8.3.min.js"></script>
<script type="text/javascript" charset="utf-8" src="cordova-2.2.0.js"></script>
<script type="text/javascript" charset="utf-8">`
// Call onDeviceReady when Cordova is loaded.
//
// At this point, the document has loaded but cordova-1.8.0.js has not.
// When Cordova is loaded and talking with the native device,
// it will call the event `deviceready`.
//
function onLoad() {
document.addEventListener("deviceready", onDeviceReady, false);
}
// Populate the database
//
function populateDB(tx) {
tx.executeSql('DROP TABLE IF EXISTS DEMO');
tx.executeSql('CREATE TABLE IF NOT EXISTS DEMO (id unique, data)');
tx.executeSql('INSERT INTO DEMO (id, data) VALUES (1, "First row")');
tx.executeSql('INSERT INTO DEMO (id, data) VALUES (2, "Second row")');
}
// Query the database
//
function queryDB(tx) {
tx.executeSql('SELECT * FROM DEMO', [], querySuccess, errorCB);
}
// Query the success callback
//
function querySuccess(tx, results) {
var len = results.rows.length;
//console.log("DEMO table: " + len + " rows found.");
$('#result').html("DEMO table: " + len + " rows found.");
var listval = '';
for (var i=0; i<len; i++){
//console.log("Row = " + i + " ID = " + results.rows.item(i).id + " Data = " + results.rows.item(i).data);
listval += '<li>'+ results.rows.item(i).data + '[' + results.rows.item(i).id + '] </li>';
}
$('#listItem').html(listval);
}
// Transaction error callback
//
function errorCB(err) {
console.log("Error processing SQL: "+err.code);
}
// Transaction success callback
//
function successCB() {
var db = window.openDatabase("Database", "1.0", "PhoneGap Demo", 200000);
db.transaction(queryDB, errorCB);
}
// Cordova is loaded and it is now safe to make calls Cordova methods
//
function onDeviceReady() {
// Now safe to use the Cordova API
//alert('ready');
var db = window.openDatabase("Database", "1.0", "PhoneGap Demo", 200000);
db.transaction(populateDB, errorCB, successCB);
//$('#result').html('hello');
}
</script>
</head>
<body onload="onLoad()">
<div>result:</div><div id="result"></div>
<ul id="listItem">
</ul>
</body>
</html>
To build on #Jeffrey's answer, I found a much cleaner way which hides the HTML markup until JQM has finished processing the page and renders the first Page element, since I've noticed that 1/2 second flicker of bare markup before JQM renders.
You only need to hide all the markup with css...PageShow() by JQM will toggle the visibility for you.
//snip
<style type="text/css">
.hide {
display:none;
}
</style>
//snip - now the markup notice the hide class
<div id="page1" data-role="page" class="hide">
//all your regular JQM / html form markup
</div>
//snip -- down to the end of /body
<script src="cordova-2.2.0.js"></script>
<script src="js/jquery-1.8.2.min.js"></script>
<script>
document.addEventListener(
'deviceready',
function () {
$(document).one("mobileinit", function () {
//any JQM init methods
});
$.getScript('js/jquery.mobile-1.2.0.min.js');
},
false);
</script>
The following worked for me on PG 2.3 and JQM 1.2, incl. Facebook Connect Plugin:
<head>
<script src="./js/jquery-1.8.2.min.js"></script>
<script>
$.ajaxSetup({
dataType : 'html'
});
var dd = $.Deferred();
var jqd = $.Deferred();
$.when(dd, jqd).done(function() {
FB.init({ appId: auth.fbId, nativeInterface: CDV.FB, useCachedDialogs: false });
});
$(document).bind('mobileinit', function () {
jqd.resolve();
});
</script>
<script src="./js/jquery.mobile-1.2.0.min.js"></script>
<script>
$.mobile.loader.prototype.options.text = "loading";
$.mobile.loader.prototype.options.textVisible = true;
$.mobile.loader.prototype.options.theme = "a";
$.mobile.loader.prototype.options.html = "";
$.mobile.ajaxEnabled = false;
$.mobile.allowCrossDomainPages = true;
$.support.cors = true;
$('[data-role=page]').live('pagecreate', function(event) {
tpl.renderReplace('login', {}, '#content-inner', function() {
auth.init();
});
});
</script>
<script src="./js/cordova-2.3.0.js"></script>
<script src="./js/cdv-plugin-fb-connect.js"></script>
<script src="./js/facebook_js_sdk.js"></script>
<!--some more scripts -->
<script>
document.addEventListener('deviceready', function() {
dd.resolve();
}, false);
</script>
<head>
Loading of PhoneGap is slightly different than loading of jQuery. jQuery works more as a utility library so you include that and it is available for use immediately. On the other hand PhoneGap requires support from native code for proper initialization so it is not ready to use soon after included in the page.
Phonegap suggests to register and wait for deviceready event executing any native specific code.
<!DOCTYPE html>
<html>
<head>
<title>PhoneGap Example</title>
<script type="text/javascript" charset="utf-8" src="lib/jquery.min.js"></script>
<script type="text/javascript">
// jquery code here
</script>
<script type="text/javascript" charset="utf-8" src="lib/android/cordova-1.7.0.js"></script>
<script type="text/javascript" charset="utf-8">
function onLoad(){
document.addEventListener("deviceready", onDeviceReady, false);
}
// Cordova is ready
function onDeviceReady() {
// write code related to phonegap here
}
</script>
</head>
<body onload="onLoad()">
<h1>Phonegap Example</h1>
</body>
</html>
For more info check doc

html-webpack-plugin output html , interior body empty

use html-webpack-plugin output html page , but in output page lost body inner html element , like <div id="app"></div> , here is my input output and webpack.config file :
input
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=0, minimum-scale=1.0, maximum-scale=1.0">
<link rel="icon" href="static/pic/logo.png" type="image/x-icon">
<link rel="stylesheet" href="static/weui/weui.min.css">
<link rel="stylesheet" href="static/index.css">
<title>APP</title>
</head>
<body>
<div id="app"></div>
<script src="./dist/vendor.js"></script>
<script src="./dist/app.js"></script>
</body>
</html>
output
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>SPA</title>
<link href="/dist/style.df241090c6a9e0a6bf26.css" rel="stylesheet"></head>
<body>
<script type="text/javascript" src="/dist/vendor.df241090c6a9e0a6bf26.js"></script><script type="text/javascript" src="/dist/app.df241090c6a9e0a6bf26.js"></script></body>
</html>
part webpack.config.js
const htmlWebpackPlugin = require('html-webpack-plugin');
plugins: [
new htmlWebpackPlugin({
title:'SPA',
filename: 'assets/index.html'
})
],
The filename option is simply used as the output file, it won't read and modify the existing file, if one exists. Because if it did that, every new build would just append to it, unless you cleaned it manually. To use your input as the base, you need to use it as a template.
new htmlWebpackPlugin({
title:'SPA',
filename: 'assets/index.html',
template: 'path/to/template/index.html'
})
The template should not be the same as the output filename, otherwise it gets overwritten. See also Writing Your Own Templates. The template can be a regular HTML file and it will inject the necessary assets.

Chrome Extension Chaing Content From the Javascript

So, I am trying to do a basic Google Chrome Hello World kind of extension. Can someone explain me why the below code doesn't work? Thanks.
popup.js:
document.getElementById("foobar").innerHTML = "Hello Chrome Extensions";
popup.html:
<!doctype html>
<html>
<head>
<title>Hello Chrome</title>
<script src="popup.js"></script>
<div id="foobar"></div>
</head>
<body>
</body>
</html>
I am following the "framework" of http://developer.chrome.com/extensions/getstarted.html.
It can be solved in two ways:
Swap the order of <script .. > and <div ..>.
Wrap the code in popup.js in a domready event:
document.addEventListener('DOMContentLoaded', function() {
// Code here...
});
Your code failed because the <div> was unknown at the time of executing the script.

Resources