Connection between content and background script for basic Chrome extension - javascript

I was hoping not to asking you for help but here I am
I want to build a simple Chrome extension which marks all paid articles on the home page.
The JS in the medium-extension.js is working through a browser console when is triggered with a button which can be found in the HTML file.
The problem is that I am confused do I need background script, because when I try without one the extension does not work. Now I try without a content script and it still does not work.
I try to do it with one of them because I don't know how to create a connection between background and content scripts.
Here is the code:
manifest.js
{
"name": "Medium cleared",
"version": "1",
"description": "Lets's make Medium great again",
"manifest_version": 2,
"browser_action": {
"default_popup": "index.html"
},
"background": {
"scripts": ["medium-extension.js"],
"persistent": false
}
}
medium-extension.js
function clearMedium() {
Array.from(
document.querySelectorAll('article')
).forEach(el => {
let shouldHide = el.querySelectorAll('span.u-paddingLeft4').length;
if (shouldHide) {
el.style.background = "#FCBFB7";
}
});
Array.from(
document.querySelectorAll('li')
).forEach(el => {
let shouldHide = el.querySelectorAll('span.u-paddingLeft4').length;
if (shouldHide) {
el.style.background = "#FCBFB7";
}
});
Array.from(
document.querySelectorAll('.extremeHero-smallCard.extremeHero-smallCard1.js-trackedPost, .extremeHero-largeCard.js-trackedPost.uiScale.uiScale-ui--small.uiScale-caption--small, .extremeHero-smallCard.extremeHero-smallCard3.js-trackedPost, .extremeHero-smallCard.extremeHero-smallCard2.js-trackedPost, .extremeHero-mediumCard.js-trackedPost')
).forEach(el => {
let shouldHide = el.querySelectorAll('span.u-paddingLeft4').length;
if (shouldHide) {
el.style.background = "#FCBFB7";
}
});
Array.from(
document.querySelectorAll('section.m.n.o.ff.q.d')
).forEach(el => {
let shouldHide = el.querySelectorAll('svg.dl.dm').length;
if (shouldHide) {
el.style.background = "#FCBFB7";
}
});
setTimeout(clearMedium, 5000);
}
<!-- begin snippet: js hide: false console: true babel: false -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<script src="medium-extension.js"></script>
<style>
.button-activate button {
background: #FF82A9;
color: white;
width: 300px;
height:50px;
font-size: 20px;
}
</style>
</head>
<body>
<div class="popup">
<h3>If you are tired of clicking on premium articles and lose one of your precios 3 free slots every month, just click "Clear your Medium" and all premium articles will be colored in red.</h3>
<div class="button-activate">
<button onclick="clearMedium()">Clear your Medium</button>
</div>
</div>
</body>
</html>

Related

how to pass dynamic URL in manifest.json in PWA

I am using PWA to add to home screen task And I doing this in php. When I click "Add to home screen button" then script run. I made changes manifest.json according php as manifest.php. I am testing it on localhost by change https by ngrok.
I am trying to pass dynamic url in manifest file.
index.html is:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<link rel="manifest" href="manifest.php">
<link rel="icon" href="favicon.ico" type="image/gif" sizes="16x16">
</head>
<body>
<h1>Hey!!</h1>
<div class="add-to">
<button class="add-to-btn">Add to home screen</button>
</div>
<script>
if ('serviceWorker' in navigator) {
console.log("Will the service worker register?");
navigator.serviceWorker.register('service-worker.js')
.then(function(reg){
console.log("Yes, it did.");
}).catch(function(err) {
console.log("No it didn't. This happened:", err)
});
}
let deferredPrompt;
var div = document.querySelector('.add-to');
var button = document.querySelector('.add-to-btn');
//div.style.display = 'none';
window.addEventListener('beforeinstallprompt', (e) => {
// Prevent Chrome 67 and earlier from automatically showing the prompt
e.preventDefault();
// Stash the event so it can be triggered later.
deferredPrompt = e;
div.style.display = 'block';
button.addEventListener('click', (e) => {
// hide our user interface that shows our A2HS button
//div.style.display = 'none';
// Show the prompt
deferredPrompt.prompt();
// Wait for the user to respond to the prompt
deferredPrompt.userChoice
.then((choiceResult) => {
if (choiceResult.outcome === 'accepted') {
console.log('User accepted the A2HS prompt');
} else {
console.log('User dismissed the A2HS prompt');
}
deferredPrompt = null;
});
});
});
</script>
</body>
</html>
manifest.php is:
<?php
$starturl = 'https://621b16b2b7c5.ngrok.io/add_to_home_screen4/images/icon192.PNG';
$manifest =
[
"short_name"=> "BetaPage",
"name"=> "BetaPage",
"theme_color"=> "#4A90E2",
"background_color"=> "#F7F8F9",
"display"=> "standalone",
"icons"=>
[
[
"src"=> "images/launcher-icon-1x.png",
"type"=> "image/png",
"sizes"=> "48x48"
],
[
"src"=> "images/launcher-icon-2x.png",
"type"=> "image/png",
"sizes"=> "96x96"
],
[
"src"=> "images/chat1.png",
"type"=> "image/png",
"sizes"=> "144x144"
],
[
"src"=> "images/icon192.png",
"type"=> "image/png",
"sizes"=> "192x192"
]
],
"start_url"=> $starturl
];
header('Content-Type: application/json');
echo json_encode($manifest);
When I reload the webpage then below error occur:
I have to press ctrl+F5 each time to run the code. Why?
I got my solution. MY service-worker.js file was not correct. Now I paste below code in service-worker.js and it wored.
self.addEventListener('fetch', function(event) {});

How do I call Javascript code from Dart and register the callback in my console?

I have a Javascript file that I'm calling in my Flutter Webview Plugin.
I am trying to return the callback in the console after the onReward method is called. This is the code of my js file:
<html>
<head>
<meta charset='utf-8'>
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no">
<meta http-equiv='X-UA-Compatible' content='IE=edge'>
<script type="text/javascript" src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<script type="text/javascript" src="https://s3.amazonaws.com/cdn.theoremreach/v3/theorem_reach.min.js"></script>
</head>
<body>
<iframe src="https://theoremreach.com/respondent_entry/direct?api_key=845783b32b8bef12f1b55a36a8be&user_id=12345"></iframe>
<script type="text/javascript">
var theoremReachConfig = {
apiKey: "",
userId: "12345",
onRewardCenterOpened: onRewardCenterOpened,
onReward: onReward,
onRewardCenterClosed: onRewardCenterClosed
};
var TR = new TheoremReach(theoremReachConfig);
function onRewardCenterOpened(){
console.log("onRewardCenterOpened");
}
function onReward(data){
console.log("onReward: " + data.earnedThisSession);
}
function onRewardCenterClosed(){
console.log("onRewardCenterClosed");
}
if (TR.isSurveyAvailable()) {
TR.showRewardCenter();
}
</script>
</body>
</html>
And this is how I'm calling it in my Dart file:
...
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text("Reward earned"), actions: [
Text("$reward"),
]),
body: WebViewPlus(
javascriptMode: JavascriptMode.unrestricted,
onWebViewCreated: (controller) {
controller.loadAsset(
'assets/tr.html',
);
},
));
}
When I complete a survey I get the following message in my console:
I/chromium( 3560): [INFO:CONSOLE(28)] "onReward: 2", source: http://localhost:56537/assets/tr.html (28)
I want to scan this console message and just add the value of the reward, i.e. 2, in my existing page and display it in the appBar.

Cannot render interactive image using gojs

I would like to create an interactive image using goJs, however when i try and follow the tutorial to create a basic visual the output I get is just a blank box and not an interactive image with the words 'Alpha' and 'Beta' connected by a line.
This is my code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src="https://unpkg.com/gojs/release/go-debug.js"></script>
<script src="go.js"></script>
<script>
function init() {
var $ = gp.GraphObject.make;
myDiagram = $(go.Diagram, "decisionTree");
var nodeDataArray = [
{ key: "Alpha" },
{ key: "Beta" }
];
var linkDataArray = [
{ to: "Beta", from: "Alpha" }
];
myDiagram.model = new go.GraphLinksModel(nodeDataArray, linkDataArray)
}
</script>
</head>
<body onload="init"()>
<div id="decisionTree" style="width:300px; height:300px; border:1px solid black;"></div>
</body>
</html>
Tutorial: https://www.youtube.com/watch?v=7cfHF7yAoJE#action=share
You are loading two different versions of the GoJS library. I suggest you remove the line:
<script src="go.js"></script>
EDIT: In addition, there are some typos that I missed before when just reading your code. This actually works:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src="https://unpkg.com/gojs/release/go-debug.js"></script>
<script>
function init() {
var $ = go.GraphObject.make;
var myDiagram = $(go.Diagram, "decisionTree");
var nodeDataArray = [
{ key: "Alpha" },
{ key: "Beta" }
];
var linkDataArray = [
{ to: "Beta", from: "Alpha" }
];
myDiagram.model = new go.GraphLinksModel(nodeDataArray, linkDataArray)
}
</script>
</head>
<body onload="init()">
<div id="decisionTree" style="width:300px; height:300px; border:1px solid black;"></div>
</body>
</html>

Vue js:ready event not working

I am trying to load a simple alert in mounted event but its not fired
Here is my code
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Test</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.1.10/vue.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue-resource/0.1.13/vue-resource.min.js"></script>
</head>
<body>
<div id="app-7">
</div>
</body>
</html>
script
new Vue({
el: '#app-7',
data: {
groceryList: [
{ text: 'Vegetables' },
{ text: 'Cheese' },
{ text: 'Whatever else humans are supposed to eat' }
],
origin:'http://s3.myimage.com/avatar.jpg'
},
mounted:function () {
console.log('ready');
alert('ok');
}
})
Also i want to set origin into an img after the page load.
Is it possible with vue??
Have you rendered it to your #app-7?
For your 2nd question, yes it's possible, you can set it up like
<img :src="origin" />
Then your img will take its source from your 'origin' string.-7

Configure the service angular-lazy-img with a dynamic scrollable container generated on controller

As a new developer on angularjs I have a specific question regarding provider. I'm trying to use the lazy load angular-lazy-load that has a specific functionality regarding the scrollable container. This scrollable container should be set in the config step.
Here is an example :
var myApp = angular.module('myApp', ['angularLazyImg']);
myApp.config(['lazyImgConfigProvider',
function(lazyImgConfigProvider) {
var scrollable = document.querySelector('.container');
lazyImgConfigProvider.setOptions({
offset: 1, // how early you want to load image (default = 100)
errorClass: 'error', // in case of loading image failure what class should be added (default = null)
successClass: null, // in case of loading image success what class should be added (default = null)
onError: function(image) {}, // function fired on loading error
onSuccess: function(image) {}, // function fired on loading success
container: angular.element(scrollable)
});
}
]);
myApp.controller('lazyCtrl', ['$scope',
function($scope) {
$scope.images = [{
url: "https://cdn.sstatic.net/stackoverflow/img/apple-touch-icon#2.png?v=73d79a89bded&a"
}, {
url: "http://www.skrenta.com/images/stackoverflow.jpg"
}, {
url: "http://sourcingrecruitment.info/wp-content/uploads/2015/05/stackoverflow.png"
}, {
url: "http://gillespaquette.ca/images/stack-icon.png"
}, {
url: "http://www.iconsdb.com/icons/preview/black/stackoverflow-3-xxl.png"
}, {
url: "https://avatars0.githubusercontent.com/u/139426?v=3&s=400"
}, {
url: "http://gillespaquette.ca/images/stack-icon.png"
} ];
}
]);
.container {
overflow: scroll;
height: 200px;
position: absolute;
}
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Example - example-guide-concepts-1-production</title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://rawgit.com/Pentiado/angular-lazy-img/master/release/angular-lazy-img.js"></script>
</head>
<body ng-app="myApp">
Test lazy image
<div ng-controller="lazyCtrl">
<div class="container">
<div ng-repeat="image in images">
<img width="100px" height="100px" lazy-img="{{image.url}}" />
</div>
</div>
</div>
</body>
But my question is how can I do to add a container option if the container element is not yet created and will be by the controller ?
Thanks in advance, please let me know which informations are missing to answer.
Ok so the trick is to add an attribut lazyImgContainer to the container in the html file. Not yet documented in github so I have added a pull request to get it documented.

Categories