Chrome Extension API v17: webRequest onErrorOccurred.addListener - redirect

I am attempting to set up a chrome extension similar to http://code.google.com/chrome/extensions/trunk/samples.html#webrequest except that it would us the onErrorOccurred listener instead to redirect to a specific known page when the get request fails for any reason.
manifest.json:
{
"name": "Custom Error",
"version": "0.1",
"description": "Redirect all navigation errors to specified location/file.",
"permissions": [
"webRequest",
"tabs",
"<all_urls>"
],
"background": {
"page": ["error_listener.html"]
}
}
error_listener.html:
<!doctype html>
<script>
chrome.webRequest.onErrorOccurred.addListener(
function onErrorOccurred(details) {
console.log('onBeforeRequest ', details.url);
return { redirectUrl: 'http://www.google.com' }
},
{urls: ["<all_urls>"]}
//{urls: ["http://*/*", "https://*/*"]}
);
//chrome.tabs.update(details.tabId, {url: "http://www.google.com", ['blocking']});
//alert("what?");
</script>
The extension loads without any errors indicated yet the browser tab is not redirected. I have tried this using both Chrome 16 and Chrome 17; when using Chrome 16, I did change "chrome.webRequest" to "chrome.experimental.webRequest" and added "experimental" to the permissions list.
So far it seems like the problem is that while the extension appears to be loaded when looking at chrome://extensions, the files are not actually loaded--when using Developer Tools, I don't see any reference to error_listener.html.
I have also tried running Chrome 17 with the following flags:
8611 25/01/12-11:22:05> google-chrome --restore-last-session
--debug-on-start --log-level=0 --enable-logging
--enable-extension-activity-logging --enable-extension-alerts
--debug-plugin-loading --debug-print | tee > log1.txt
Obviously, I am just kind of poking around in the dark with that command line. Anyone have any clue as to how to get this working? Thanks in advance for your help!

There is no webRequest.onErrorOccurred event. You may use webNavigation.onErrorOccurred. If you want to catch DNS errors and redirect to another url you may use the code:
<script>
chrome.webNavigation.onErrorOccurred.addListener(function(details)
{
if (details.frameId != 0) //ignore subframes. 0 is main frame
{ return; }
chrome.tabs.update(details.tabId, {url: "https://www.google.com/search?q=" + details.url});
});
</script>

In Chrome 16, you should be using:
"background_page": "background.html"
rather than
"background": {
"page": ["error_listener.html"]
}
This fixes the problem with the background page not loading. It looks like this may have changed in the trunk docs compared to the current docs, and I'm not sure which version of Chrome starts implementing the new manifest.json format.

Related

Images in Strapi media library not showing

I just deployed my strapi cms to heroku, and the problem is when I add assets into media library, the images will not showing after few minutes, it looks like this
The URL of the images exists on the API, but when I check it manually, it shown 'not found' message. Any solution of this case?
This Issue may be solved. According to the #strapi/provider-upload-cloudinary documentation
According to that, we need to add the below code to ./config/middlewares.js file.
module.exports = [
// ...
{
name: 'strapi::security',
config: {
contentSecurityPolicy: {
useDefaults: true,
directives: {
'connect-src': ["'self'", 'https:'],
'img-src': ["'self'", 'data:', 'blob:', 'dl.airtable.com', 'res.cloudinary.com'],
'media-src': ["'self'", 'data:', 'blob:', 'dl.airtable.com', 'res.cloudinary.com'],
upgradeInsecureRequests: null,
},
},
},
},
// ...
];
This should resolve the issue and we should be able to see the image thumbnails in the Strapi media library.

PWA - beforeinstallprompt not called

Hello I'm trying to install a custom PWA "Add to Homescreen".
The ServiceWorkerRegistration is successful.
But the function beforeinstallpromp is not calling after register.
<script type="text/javascript">
function request_debug(paramdata){
document.getElementById('output').innerHTML += '<BR>'+ paramdata;
}
window.addEventListener('load', function() {
document.getElementById('output').style.display = "block";
if('serviceWorker' in navigator) {
navigator.serviceWorker.register('sw.js').then(function(registration) {
console.log('Service worker registrado com sucesso:', registration);
request_debug(registration);
}).catch(function(error) {
console.log('Falha ao Registrar o Service Worker:', error);
request_debug(error);
});
var isTooSoon = true;
window.addEventListener('beforeinstallprompt', function(e) {
//e.preventDefault();
//e.prompt();
//promptEvent = e;
request_debug(' window.addEventListener beforeinstallprompt fired!')
if (isTooSoon) {
//e.preventDefault(); // Prevents prompt display
// Prompt later instead:
setTimeout(function() {
isTooSoon = false;
e.prompt(); // Throws if called more than once or default not prevented
}, 4000);
}
});
}else{
console.log('serviceWorker not in navigator');
request_debug('serviceWorker not in navigator');
}
});
</script>
Also my service worker in root directory...
HTTPS is secure!
my manifest:
{
"background_color": "purple",
"description": "lojaportaldotricot TESTE",
"display": "standalone",
"icons": [
{
"src": "/componentes/serviceWorker/fox-icon.png",
"sizes": "192x192",
"type": "image/png"
}
],
"name": "lojaportaldotricot",
"short_name": "lojaportaldotricot",
"start_url": "/dashboard"
}
It's only workes when I set "Enable" chrome://flags/#bypass-app-banner-engagement-checks
Edit: Look's like I've found the problem. The Audits tabs of Chrome's DevTools(F12) gives debugging information.
Try this :
<script>
let deferredPrompt;
window.addEventListener('beforeinstallprompt', function(event) {
// Prevent Chrome 67 and earlier from automatically showing the prompt
e.preventDefault();
// Stash the event so it can be triggered later.
deferredPrompt = e;
});
// Installation must be done by a user gesture! Here, the button click
btnAdd.addEventListener('click', (e) => {
// hide our user interface that shows our A2HS button
btnAdd.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>
beforeinstallprompt will only be fired when some conditions are true :
The PWA must not already be installed
Meets a user engagement heuristic (previously, the user had to interact with the domain for at least 30 seconds, this is not a requirement anymore).
Your web app must include a web app manifest.
Your web app must be served over a secure HTTPS connection.
Has registered a service worker with a fetch event handler.
Along with all of those steps above, also check that the app is uninstalled here:
chrome://apps
Just deleting the app from the Chrome Apps folder on your Mac does not seem to remove it from Chrome
If the app was previously installed, the beforeinstallprompt will not be triggered, and no errors will be thrown either :(
Yes, the "start_url" is incorrect in the manifest.
IF ANY PART OF THE MANIFEST IS BROKEN 'beforeinstallprompt' is not fired.
The event is not fired because... the manifest start_url is incorrect.
My favorite way to figure this out is to look in the > NETWORK tab of DevTools for 404's.
AND the other way to see why manifest is broken is to run > AUDIT in DevTools and see what the error is. Like what #sealabr found:
"Failures: Service worker does not successfully serve the manifest's start_url, Timed out waiting for fetched start_url.' Which means the 'start_url"
This thread was a big help troubleshooting production. Thanks.
Are you including the manifest file in the page header?
<link rel="manifest" href="/manifest.json">
To whoever needs to read this: A little side-note that I ran into when working on my Vue3 app while trying to figure out the prompt:
The beforeInstallPrompt will trigger shortly after the page load.
So make sure you set up the event listener close to the page load. Took me a couple of hours to find this out. I was trying to add the event listener somewhere down the line of onboarding the user. Way after the page load. And couldn't figure out why the prompt didn't show.
here is another reason why beforeinstallprompt is not triggered on a mobile device (observed on an Android device with Chrome):
A symbol file defined in manifest.webmanifest could not be found on the web server (the mobile browser reported a 404). That was the reason why beforeinstallprompt was not triggered in my case.
#example
// your manifest
{
/* ... */
"icons": [
{
"src": "maskable_icon_x192.png",
"sizes": "192x192",
"type": "image/png",
"purpose": "any maskable"
},
/*...*/
]
}
Make sure that all icon files (such as maskable_icon_x192.png) are present on your web server.
All the best,
Tom

Can't reload the opened page in a Chrome App

I'm trying to update a page in a Chrome App but I get the error:
Can't open same-window link to "chrome-extension://XXXX/page.html"; try target="_blank".
My manifest.json:
"app": {
"background": {
"scripts": [ "background.js" ]
},
"persistent": false
},
my background.js:
chrome.app.runtime.onLaunched.addListener(function() {
chrome.app.window.create('page.html', {
'outerBounds': {
'width': 7000,
'height': 7000
}
});
});
and a window.location.reload(); in page.js
P.S.: I considered chrome.runtime.reload();, but it will restart the window/browser, I just wanted to refresh the page without the window closing and opening.
I've created another page "main.html" and I'm loading the "page.html" from that one on an iframe and I'm able to reload it that way,
Just posting my own solution in hope that it might help someone.

Google Actions SDK Sign-In implicit flow

EDIT: On phone assistant its working now problem just exist in google action simulator
I just try to setup Google Actions SDK account Linking with implicit grant and try to test it in Simulator.
First question is this even possible in Simulator?
To Do so I added at the action console account linking with the type
implicit grant to my action.
The url I used is working.
Now I added a signup request to my action. For testing so if I write signup in simulator the server response with:
{
conversationToken: JSON.stringify(state),
expectUserResponse: true,
expectedInputs: [
{
inputPrompt: {
initialPrompts: [
{
textToSpeech: "PLACEHOLDER_FOR_SIGN_IN"
}
],
noInputPrompts: []
},
possibleIntents: [
{
"intent": "actions.intent.SIGN_IN",
"inputValueData": {}
}
],
speechBiasingHints: []
}
]
}
After this the server didn't request the sign in page route (the address is correct!). It just responds with SignIN intent ERROR :
{
"isInSandbox'": false,
"surface": {
"capabilities": [
{
"name": "actions.capability.AUDIO_OUTPUT"
},
{
"name": "actions.capability.SCREEN_OUTPUT"
}
]
},
"inputs": [
{
"rawInputs": [
{
"query": "i think so",
"inputType": "VOICE"
}
],
"arguments": [
{
"name": "SIGN_IN",
'extension': {
"#type": "type.googleapis.com/google.actions.v2.SignInValue",
"status": "Error"
}
}
],
"intent': "actions.intent.SIGN_IN"
}
],
"device": {
"locale": "en-US"
},
"conversation": {
"conversationId": "1494606917128",
"type": "ACTIVE",
"conversationToken": "[\"_actions_on_google_\"]"
}
}
Why? Where is the problem? Can I see a error message somewhere?
Here is what happen in the simulator between 3 and 4:
Is it same when you use the phone app? For me it opens an embedded browser with my /auth endpoint, which the simulator doesn’t do.
I am able to make it WORKING after a long time.
We have to enable the webhook first and we can see how to enable the webhook in the dialog flow fulfillment docs
If we are going to use Google Assistant, then we have to enable the Google Assistant Integration in the integrations first.
Then follow the steps mentioned below for the Account Linking in actions on google:-
Go to google cloud console -> APIsand Services -> Credentials -> OAuth 2.0 client IDs -> Web client -> Note the client ID, client secret from there
-> Download JSON - from json note down the project id, auth_uri, token_uri
-> Authorised Redirect URIs -> White list our app's URL -> in this URL fixed part is https://oauth-redirect.googleusercontent.com/r/ and append the project id in the URL
-> Save the changes
Actions on Google -> Account linking setup
1. Grant type = Authorisation code
2. Client info
1. Fill up client id,client secrtet, auth_uri, token_uri
2. Enter the auth uri as https://www.googleapis.com/auth and token_uri as https://www.googleapis.com/token
3. Save and run
4. It will show an error while running on the google assistant, but dont worry
5. Come back to the account linking section in the assistant settings and enter auth_uri as https://accounts.google.com/o/oauth2/auth
and token_uri as https://accounts.google.com/o/oauth2/token
6. Put the scopes as https://www.googleapis.com/auth/userinfo.profile and https://www.googleapis.com/auth/userinfo.email
and weare good to go.
7. Save the changes.
In the hosting server logs, we can see the access token value and through access token, we can get the details regarding the email address.
Append the access token to this link "https://www.googleapis.com/oauth2/v1/userinfo?access_token=" and we can get the required details in the resulting json page.
accessToken = req.get("originalRequest").get("data").get("user").get("accessToken")
r = requests.get(link)
print("Email Id= " + r.json()["email"])
print("Name= " + r.json()["name"])
P.S. You can use the Grant Type as Implicit also instead of Authorisation code.

How to use Ionic proxy in conjunction with AWS SDK

Using Ionic 4.4.0 and aws-sdk 2.157.0. I'm trying to create an S3 bucket from my local web browser, but am running into CORS problems when attempting to run the following code, method createBucketByCompanyKey():
import { Injectable } from '#angular/core';
import * as AWS from 'aws-sdk';
#Injectable()
export class AwsProvider {
private accessKeyId:string = 'myAccessKey';
private secretAccessKey:string = 'mySuperSecret';
private region:string = 'us-east-1';
constructor() {
AWS.config.update({accessKeyId: this.accessKeyId, secretAccessKey: this.secretAccessKey, region: this.region});
}
createBucketByCompanyKey(companyKey){
let s3 = new AWS.S3();
let params = {
Bucket: companyKey,
CreateBucketConfiguration: {
LocationConstraint: this.region
}
};
s3.createBucket(params, function(err, data) {
if (err) console.log(err, err.stack); // an error occurred
else console.log(data); // successful response
});
}
}
This gives me the error
Failed to load https://s3.amazonaws.com/-KwzdjmyrHiMBCqHH1ZC: Response
to preflight request doesn't pass access control check: No
'Access-Control-Allow-Origin' header is present on the requested
resource. Origin 'http://localhost:8100' is therefore not allowed
access. The response had HTTP status code 403.
Which led me to this post here after several hours of googling. It appears I need to run ionic through a proxy. I've also tried changing my "path" to http://localhost:8100, but stuck I remain.
{
"name": "MyApp",
"app_id": "",
"type": "ionic-angular",
"integrations": {},
"proxies": [
{
"path": "/",
"proxyUrl": "https://s3.amazonaws.com/"
}
]
}
I've also come across posts telling my to download a Chrome extension that disables CORS, but that didn't work either.
Any ideas on how to setup this proxy to work with AWS' SDK?
Forget the proxies. For Mac, enter in the following in the terminal to open a Google Chrome browser with CORS disabled.
open -a Google\ Chrome --args --disable-web-security --user-data-dir
Compliments of this post.