Send message from app (popup.js) to JS (content.js) in Safari Web Extension (iOS 15) - ios

I'm having trouble with a simple task. In Xcode 13, you can create a Safari Extension App (Safari Web Extension for iOS 15).
From looking around, the Shared Extension has various js resources: background.js, content.js, and popup.js.
Popup.js is the presented modal when you launch your Safari web extension. In popup.html, you can add elements to the popup DOM (such as text, button, etc). In my popup, I have a button which I have wired up in popup.js. When I press this button, I want to notify content.js of this event. How do I do this?
My current code adds an event listener to the button containing browser.runtime.sendMessage({ type: "start" }); in popup.js.
Xcode's template includes the following in content.js:
browser.runtime.sendMessage({ greeting: "hello" }).then((response) => {
console.log("Received response: ", response);
});
browser.runtime.onMessage.addListener((request, sender, sendResponse) => {
console.log("Received request: ", request);
});
As far as I can tell, the JS is running in popup.js, but I am not seeing anything in console.log for content.js. Sidenote: console.log is really hard to use for iPhone Safari app.
I've found this documentation, but it only discusses passing message from macOS app to JS. I'm trying to pass message from iOS popup to content.js.

See if this works
const isChrome = !window["browser"] && !!chrome;
const browser = isChrome ? chrome : window["browser"];
function sendMessageToContent(message) {
browser.tabs.query({ active: true }).then(function (currentTabs) {
if (currentTabs[0].id >= 0) {
browser.tabs.sendMessage(currentTabs[0].id, message);
}
});
}

Related

Can't interact with chrome extension page with playwright

I want to automate metamask chrome extension with playwright. I found the code below in the API document. I'm able to load Metemask extension but when I try to click the Get Started button on the metamask home page it shows timeout error waiting for the selector.
I need help to check what is the problem and how to work with backgroundpage
(async () => {
const pathToExtension = require('path').join(__dirname, 'my-extension');
const userDataDir = '/tmp/test-user-data-dir';
const browserContext = await chromium.launchPersistentContext(userDataDir,{
headless: false,
args: [
`--disable-extensions-except=${pathToExtension}`,
`--load-extension=${pathToExtension}`
]
});
const backgroundPage = browserContext.backgroundPages()[0];
// Test the background page as you would any other page.
await backgroundPage.click('.btn-primary') // Get Started button
await browserContext.close();
})();
Background page is invisible and doesn't have the button you are trying to click. What you need is to be able to click on elements inside the extension popup window which is currently not supported. Please thumb up this feature request https://github.com/microsoft/playwright/issues/5593 if you need it.

Open a link from a webview in a chrome app within the same webview

I am trying to create a chrome kiosk app that will open a webpage that contains links in a webview and then load the links within the same webview. However, the links on the webpage that I am working with are target="_blank" and I am getting the error <webview>: A new window was blocked wehn they are clicked. I found a solution to this here and tried to implement its suggestion like this:
chrome.app.runtime.onLaunched.addListener(function() {
chrome.app.window.create(
'window.html',
{ 'width': 1000, 'height': 1000 },
function(win) {
win.contentWindow.onload = function() {
var webview = win.contentWindow.document.querySelector('#webview');
webview.addEventListener('newwindow', function(e) {
chrome.app.window.create(e.targetUrl,window.open()
});
};
}
);
});
However, I would like to have the link open not in the browser, but in the same webview that the link was launched from.
Is there some way to capture the target URL, strip it of its target="_blank" attribute, and then load the URL in the original webview?
An event listener in the content script will capture the URL when the newwindow event is fired. Once the URL is captured, it's a simple thing to set the URL as the webview's source.
var webview = document.querySelector('#webview');
webview.addEventListener('newwindow', function (e) {
//prevent the link from attempting to open a new window
e.preventDefault();
webview.src = e.targetUrl;
});
Because this script doesn't open any new windows, it doesn't have to be run specifically in the app's background script.

externally_connectable and Firefox WebExtensions

I am trying to convert a Chrome Extension to Firefox using the new API WebExtension.
Everything works fine except the use of chrome.runtime.sendMessage() in a webpage. The goal is to communicate with the addon and pass some data.
For that, I am using the property "externally_connectable" as written here : can-a-site-invoke-a-browser-extension
background.js
chrome.runtime.onMessageExternal.addListener(
function(request, sender, sendResponse) {
sendResponse({
success: true,
message: 'ok'
});
return true; // Bug chrome, close channel otherwise
});
In webpage
chrome.runtime.sendMessage(EXTENSION_ID, {type: 'show', data: 'test'}, function(response) {
if (response.success && !response.success) {
console.log(response.message);
}
});
In chrome, the communication works fine but in Firefox, the code executed in the webpage doesn't work : "chrome is not defined".
Is there another var to use instead of "chrome" or is it not implemented ?
I've found nothing about this on the web :( Thanks
Web extensions do not support externally_connectable website scripts but you can communicate between website scripts and extension scripts as shown in this example
https://github.com/mdn/webextensions-examples/tree/master/page-to-extension-messaging
Try use WebExtension APIs with "browser" namespace
browser.runtime.sendMessage(...)
All available APIs on mozilla development
https://developer.mozilla.org/en-US/Add-ons/WebExtensions/Content_scripts#WebExtension_APIs

PhoneGap InAppBrowser: open iOS Safari Browser

In our PhoneGap iOS application, we are using the InAppBrowser plugin to display some content, and we need to open a page in Safari from within the InAppBrowser.
How can we have links from within the InAppBrowser open in Safari?
From the phonegap documentation:
Opens a URL in a new InAppBrowser instance, the current browser instance, or the system browser.
var ref = window.open(url, target, options);
ref: Reference to the InAppBrowser window. (InAppBrowser)
url: The URL to load (String). Call encodeURI() on this if the URL contains Unicode characters.
target: The target in which to load the URL, an optional parameter that defaults to _self. (String)
_self: Opens in the Cordova WebView if the URL is in the white list, otherwise it opens in the InAppBrowser.
_blank: Opens in the InAppBrowser.
_system: Opens in the system's web browser.
So to answer your question, use:
window.open(your_url, '_system', opts);
Note that the domain will need to be white-listed.
Update 4/25/2014:
I think I kind of misunderstood the question (thanks to commenter #peteorpeter) -- you want to have some way to click a link in the InAppBrowser and have that open in the system browser (e.g. Mobile Safari on iOS). This is possible, but it will require some forethought and cooperation between the app developer and the person responsible for the links on the page.
When you create an IAB instance, you get a reference to it back:
var ref = window.open('http://foo.com', '_blank', {...});
You can register a few event listeners on that reference:
ref.addEventListener('loadStart', function(event){ ... });
This particular event is fired every time the URL of the IAB changes (e.g. a link is clicked, the server returns a 302, etc...), and you can inspect the new URL.
To break out into the system browser, you need some sort of flag defined in the URL. You could do any number of things, but for this example let's assume there's a systemBrowser flag in the url:
.....html?foo=1&systemBrowser=true
You'll look for that flag in your event handler, and when found, kick out to the system browser:
ref.addEventListener('loadStart', function(event){
if (event.url.indexOf('systemBrowser') > 0){
window.open(event.url, '_system', null);
}
});
Note that this is not the best method for detecting the flag in the url (could lead to false positives, possibly) and I'm pretty sure that PhoneGap whitelist rules will still apply.
Unfortunately target=_system does not work from within the InAppBrowser. (This would work if the link originated in the parent app, though.)
You could add an event listener to the IAB and sniff for a particular url pattern, as you mention in your comments, if that fit your use case.
iab.addEventListener('loadstart', function(event) {
if (event.url.indexOf("openinSafari") != -1) {
window.open(event.url, '_system');
}
}
The 'event' here is not a real browser event - it is a construct of the IAB plugin - and doesn't support event.preventDefault(), so the IAB will also load the url (in addition to Safari). You might try to handle that event within the IAB, with something like:
iab.addEventListener('loadstop', function(event) {
iab.executeScript('functionThatPreventsOpenInSafariLinksFromGoingAnywhere');
}
...which I have not tested.
This message is for clarification:
If you open an another with window.open by catching a link on loadstart, it will kill yor eventhandlers that assigned to first IAB.
For example,
iab = window.open('http://example.com', '_blank', 'location=no,hardwareback=yes,toolbar=no');
iab.addEventListener('loadstop', function(event) {console.log('stop: ' + event.url);});
iab.addEventListener('loaderror', function(event) { console.log('loaderror: ' + event.message); });
iab.addEventListener('loadstart', function(event) {
if (event.url.indexOf("twitter") != -1){
var ref2 = window.open(event.url, '_system', null);
}
});
When the second window.open executed, it will kill all the event listeners that you binded before. Also loadstop event will not be fired after that window.open executed.
I'm finding another way to avoid but nothing found yet..
window.open() doesn't work for me from within an InAppBrowser, whether or not I add a script reference to cordova.js to get support for window.open(...'_system'), so I came up with the following solution which tunnels the "external" URL back to the IAB host through the hashtag so it can be opened there.
Inside the InAppBrowser instance (I'm using AngularJS, but you can replace angular.element with jQuery or $ if you're using jQuery):
angular.element(document).find('a').on('click', function(e) {
var targetUrl = angular.element(this).attr('href');
if(targetUrl.indexOf('http') === 0) {
e.preventDefault();
window.open('#' + targetUrl);
}
});
Note that that's the native window.open above, not cordova.js's window.open. Also, the handler code assumes that all URLs that start with http should be externally loaded. You can change the filter as you like to allow some URLs to be loaded in the IAB and others in Safari.
Then, in the code from the parent that created the InAppBrowser:
inAppBrowser.addEventListener('loadstart', function(e) {
if(e.url.indexOf('#') > 0) {
var tunneledUrl = e.url.substring(e.url.indexOf('#') + 1);
window.open(tunneledUrl, '_system', null);
}
});
With this solution the IAB remains on the original page and doesn't trigger a back-navigation arrow to appear, and the loadstart handler is able to open the requested URL in Safari.

Links will not open in iframe target in an iOS standalone web app

I am running into a pickle. When I view my web app within mobile safari via iOS 6, I am able to successfully open up my basic target links <a href="link.html" target="mainframe"into my retrospective iframe <iframe src="http://www.linkexample.org/" name="mainframe"></iframe>
Though when the app is opened via standalone all the links exit out of the app and into Mobile Safari. You can see a working example at http://lacitilop.com/m2
Anyone have any suggestions on how to fix this?
You'll need to write some javascript to change the src of the iframe.
For a start, get your app working so that links will not open Safari by using something like the following (it's using jquery by the way):
if (window.navigator.standalone) {
$(document).on(
"click",
"a",
function (event) {
event.preventDefault();
var aurl = $(event.target).attr("href");
if (aurl) {
location.href = $(event.target).attr("href");
}
else {
location.href = this;
}
}
);
}
then you'll need to modify it to work with iframes too.
For more iphone app stuff you'll want to look at this:
http://developer.apple.com/library/safari/#documentation/AppleApplications/Reference/SafariWebContent/ConfiguringWebApplications/ConfiguringWebApplications.html

Resources