Safari Extension: change webpage styles or DOM when button is clicked - safari-extension

I'm making a Safari extension, but am not able to make any visible changes to the webpage using JS injection.
I have added a button in Extension Builder. This is global.html:
safari.application.addEventListener("command", performCommand, false);
function performCommand(event) {
document.getElementsByTagName("body")[0].style.background = "red";
alert('no errors!'); // this IS called
}
The alert IS called so the function is executed without errors. However, the body background does not become red. I have tried with different webpages. If I change the body background with Safari's Web Inspector then the page becomes red. The JS by itself is fine: https://jsfiddle.net/f1tdx3za/
In Extension Builder:
Website Access: all (checked 'include secure pages')
Note that the DOM change must be linked to the button click. It should NOT be executed whenever a page loads.

Related

Make a page scroll to the bottom of a certain div tag when using Nuxt, Apollo, and fetchMore method

I used the fetchMore method for pagination in Nuxt, which loads more posts. I got the posts to load properly but I noticed the page reloads and starts back at the top of the page. How do I get the page to scroll automatically to a specific div tag after clicking my button (which uses the fetchMore method on click)?
I tried this inside the method but it didnt' work for me:
var container = this.$el.querySelector("#container");
container.scrollTop = container.scrollHeight;

Safari Extension: window.open(...) doesn't work sometimes?

I have an injected stylesheet that calls a popup with window...open() on two occasions. One when the user clicks an HTML button, and two, when a user clicks on a context menu item. To listen for the context menu item, I need to add a listener on the injected script like so
safari.self.addEventListener("message", messageCallBack, false); // Message comes from global.html when context menu item is clicked
And the following callback
function messageCallBack(msgEvent) {
...
window.open(...)
...
}
For some reason, the popup works when the button calls window.open, but NOT when the message callback calls window.open. I'm assuming it maybe have something to do with the window object.
I suspect this is due to restrictions on window.open designed to combat pop-up ads. This means it will only work in response to a click event.
To get around this, I would recommend you open the new window from your global page using the safari.application API:
safari.application.openBrowserWindow();
safari.application.activeBrowserWindow.activeTab.url = '...';
You can also open new tabs with:
safari.application.activeBrowserWindow.openTab('foreground').url = '...';
To achieve this, you may need to send a message from your injected script to the global page.

Reloading a page in WinJS fails to attach event handlers

I have a WinJS application (a Windows 8.1 app using HTML/JS, not C#/XAML).
I've implemented a custom navbar in my default.html, with some buttons that have click event listeners attached to them. Each handler calls nav.navigate() with the url of the page corresponding to the nav button.
One of my pages (call it /pages/myPage/myPage.html) has several buttons on it. Each button has a click event listener bound to it in the page's ready function. This works fine when navigating between several pages.
However, if I'm on myPage (with working button click handlers) and click the navbar button for myPage again, the page looks like it reloads. The ready function seems to be called (i.e. it console.log statements in it are executed), but the buttons on the page seem to completely lose their click handlers!
If I navigate to another page, then navigate back, the buttons work fine again. But no matter what I do, "reloading" the page by navigating to itself (nav.navigate("/pages/myPage/myPage.html") while on myPage) causes my click handlers to be lost.
Why does this happen? My ready function is called, but somehow the click handlers are never re-attached.
Here's what the ready function for myPage looks like:
ready: function (element, options) {
document.getElementById("myButton").addEventListener("click", this.myButtonClicked);
},
Here's what the click event listener for the myPage nav button looks like (this code is in default.js):
myPageNavButton.addEventListener("click", function () {
nav.navigate('/pages/myPage/myPage.html');
});
Page nav in WinJS is just a matter of DOM replacement. When you do a nav, the target “page” contents are loaded into the DOM and then the previous “page’s” contents are unloaded. You can see this in navigator.js in the _navigating method. It creates a new element for the page being loaded, renders that fragment therein, and then unloads the old page.
The ready method for the new page, however, is called before the old page is unloaded (this was a change in WinJS 2.0, as WinJS 1.0 unloaded the old page before calling ready). The upshot of this is that when you navigate to the same page that’s already loaded, myPage.html(A) is in the DOM when you load myPage.html(B). When you execute the code in your ready method, then, getElementById will find the buttons in myPage.html(A) and so you're attaching handlers to that element. But then after you return from ready, myPage.html(A) is unloaded, so you lose the handlers. And because you never attached handlers to the buttons in myPage.html(B), they're just inert.
So what can you do about it? The best solution, in my mind, is to avoid navigating to the same page in the first place, because it's just fraught with other peril in the long run. To do this, wrap your call to nav.navigate with a check for whether you're already on the target page. Here's an implementation of a function that does that:
function navigateIfDifferent(target) {
var page = document.getElementById("contenthost").winControl.pageControl;
var fullTarget = "ms-appx://" + Windows.ApplicationModel.Package.current.id.name + target;
if (fullTarget !== page.uri) {
WinJS.Navigation.navigate(target);
}
}
This assumes that the PageControlNavigator control that you're using is in a div called "contenthost" in default.html (which is what the VS template gives you). What I'm then doing is building the full in-package URI for the target page and comparing that to the uri of the current page control, which is also a full in-package URI. You could also strip off the ms-appx:// part from the current page URI and compare to the target URI. Either way.
Anyway, with this function, replace your calls to nav.navigate with navigateIfDifferent, and you should be good.

Durandal view no more displayed if user click quickly on menus

I use Durandal 2.0 & Breeze in my SPA.
I have a sidebar menu for my drivers (Chauffeurs) where user can click on submenus (Récents, Disponibles, Indisponibles) for calling my view with different parameters. This will fill a koGrid with data. The data is fetched in the activate call and the binding of the koGrid is done in the compositionComplete.
Everything goes well most of the time. Things goes wrong when I click very quickly on submenus (calling the same view). Example: I click on 'Récents' and immediately (without waiting for the view to display) I click on 'Disponibles'.
I have the following for the activate:
var activate = function (filterParam) {
filter(filterParam);
pagedDataSource.getDataFunction = getData;
pagedDataSource.getPredicatesFunction = getPredicates;
return pagedDataSource.reload();
};
And I have the following code for the compositionComplete:
var compositionComplete = function (view) {
bindEventToList(view, '.kgCellText', gotoDetails);
$('#mySearchGrid').attr('data-bind', 'koGrid: gridOptions');
ko.applyBindings(vm, document.getElementById('mySearchGrid'));
};
When I trace the activity, I noted that if user click quickly on submenus, the activate does not have the time to finish and is called again (for the second click of the user) and the compositionComplete does not execute. Then after that, nothing more happened visually. It seems blocked.
Any idea how can I prevent this problem?
Thanks.
The migration to the latest Durandal version 2.0.1 fixed the problem.

Dynamic menu button items in TinyMCE

I have a custom menubutton in my tinyMCE editor that uses specific HTML elements elsewhere on the page as the menu items. I use a jQuery selector to get the list of elements and then add one each as a menu item:
c.onRenderMenu.add(function(c,m) {
m.add({ title: 'Pick One:', 'class': 'mceMenuItemTitle' }).setDisabled(1);
$('span[data-menuitem]').each(function() {
var val = $(this).html();
m.add({
title: $(this).attr("data-menuitem"),
onclick: function () { tinyMCE.activeEditor.execCommand('mceInsertContent', false, val) }
});
});
});
My problem is that this only happens once when the button is first clicked and the menu is first rendered. The HTML elements on the current page will change occasionally based on user clicks and some AJAX, so I need this selector code to run each time the menu is rendered to make sure the menu is fully up-to-date. Is that possible?
Failing that, is it possible to dynamically update the control from the end of my AJAX call elsewhere in the page? I'm not sure how to access the menu item and to update it. Something using tinyMCE.activeEditor.controlManager...?
Thanks!
I found a solution to this problem, though I'm not sure it's the best path.
It doesn't look like I can make tinyMCE re-render the menu, so instead I've added some code at the end of my AJAX call: after it has updated the DOM then it manually updates the tinymce drop menu.
The menu object is accessible using:
tinyMCE.activeEditor.controlManager.get('editor_mybutton_menu')
where mybutton is the name of my custom control. My quick-and-dirty solution is to call removeAll() on this menu object (to remove all the current menu items) and then to re-execute my selector code to find the matching elements in the (new) DOM and to add the menu items back based on the new state.
It seems to work just fine, though tweaks & ideas are always welcome!